Mr. Alien
Mr. Alien

Reputation: 157304

How do we select first occurence of an element in the entire document using CSS

This question stumped me

Say suppose we have a structure like this

<!-- Elements can be dynamic -->
<div>
  <section>

  </section>
  <section>
    <p>1st Para</p>
  </section>
  <section>
    <p>2nd Para</p>
  </section>
  <section>

  </section>
</div>

Now in this case how do I select only 1st instance of p element?

Note: Sections can be dynamic so

div section:nth-of-type(2) p {
   /* This won't work */
}

Upvotes: 4

Views: 179

Answers (2)

Ebrahim Khalil
Ebrahim Khalil

Reputation: 37

use p:first , p:second and it will work like a class but you don't need to add .anyclass in yout html tag. Hope this helps.

Upvotes: 0

Chris Bier
Chris Bier

Reputation: 14437

This is not possible using CSS alone. You mentioned that the elements get dynamically generated, if that is the case then I would programmatically put a class on the first <p> and target it that way.

By doing this you will also ensure cross-browser compatibility; since if it were possible, you would most definitely have to use CSS3 pseudo-classes.

Upvotes: 4

Related Questions