Jump to content
Search Community

One of several identical classes

qqignatqq test
Moderator Tag

Warning: Please note

This thread was started before GSAP 3 was released. Some information, especially the syntax, may be out of date for GSAP 3. Please see the GSAP 3 migration guide and release notes for more information about how to update the code to GSAP 3's syntax. 

Recommended Posts

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
Link to comment
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
Link to comment
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
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...