Search code examples
csscss-selectorspseudo-class

How to select the first, second, or third element with a given class name?


How can I select a certain element in a list of elements? I have the following:

<div class="myclass">my text1</div>
<!-- some other code follows -->
<div>
    <p>stuff</p>
</div>
<div>
    <p>more stuff</p>
</div>
<p>
    <span>Hello World</span>
</p>
<div class="myclass">my text2</div>
<!-- some other code follows -->
<div>
    <p>stuff</p>
</div>
<p>
    <span>Hello World</span>
</p>
<input type=""/>
<div class="myclass">my text3</div>
<!-- some other code follows -->
<div>
    <p>stuff</p>
</div>
<footer>The end</footer>

I have the CSS class div.myclass {doing things} that applies to all, obviously, but I also wanted to be able to select the first, second, or third div of class .myclass like this, regardless of where they are in the markup:

div.myclass:first {color:#000;} 
div.myclass:second {color:#FFF;} 
div.myclass:third {color:#006;}

Almost like the jQuery index selection .eq( index ), which is what I am using currently, but I need a no-script alternative.

To be specific, I am looking for pseudo selectors, not things like adding another class or using IDs to make things work.


Solution

  • You probably finally realized this between posting this question and today, but the very nature of selectors makes it impossible to navigate through hierarchically unrelated HTML elements.

    Or, to put it simply, since you said in your comment that

    there are no uniform parent containers

    ... it's just not possible with selectors alone, without modifying the markup in some way as shown by the other answers.

    You have to use the jQuery .eq() solution.