Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...
qqignatqq

One of several identical classes

Recommended Posts

If there are several identical classes, can we refer to, for example, the third one?

<div class="anyclass">NOT THIS</div>
<div class="anyclass">NOT THIS</div>
<div class="anyclass">---THIS---</div>
<div class="anyclass">NOT THIS</div>

Share this post


Link to post
Share on other sites

If you know the index position of the element it should be something as simple as this:

 

document.querySelector(".anyclass:nth-child(3)");

If you don't then you'll have to do a querySelectorAll(".anyclass") and then iterate through that collection and find a specific attribute in the targeted element.

 

Happy Tweening!!!

  • Like 4

Share this post


Link to post
Share on other sites

Keep in mind that querySelector and querySelectorAll follow the same rules as CSS selectors for element selection. So Rodrigo's suggestion selects the first .anyclass element that is the third div in a section. It would not work in the case of the following:

 

<span>Something else</span>
<div class="anyclass">NOT THIS</div>
<div class="anyclass">NOT THIS</div>
<div class="anyclass">---THIS---</div>
<div class="anyclass">NOT THIS</div>

This is not an error, it's just how selection works. :nth-of-type might be more useful in cases like this but still could have issues depending on your markup.

 

Most of the time if you need to select a particular element it is more failsafe to add an ID or unique class and select it using that. 

  • Like 2

Share this post


Link to post
Share on other sites
document.querySelectorAll(".anyclass")[2]

?

Share this post


Link to post
Share on other sites
7 minutes ago, qqignatqq said:

document.querySelectorAll(".anyclass")[2]

?

That would work (it's slightly less performant but you shouldn't notice in the vase majority of cases) if you only have these elements on the page. If you have multiple sets you could do the same but use the container as a reference instead of the document

  • Like 2

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

  • Recently Browsing   0 members

    No registered users viewing this page.

×