0

I have a lot of element in one div, for ex:

<div>
  <p></p>
  <span></span>
  <div class="text"></div>
  <span></span>
  <div class="text"></div>
  <div class="text"></div>

I want to select the first .text so I used .text:first-of-type but it doesn't work, only works for span:first-of-type
Can anybody show me how to select the first .text ?

user3761386
  • 49
  • 2
  • 10
  • with pure CSS? Not possible. There is no` first-of-class` selector. There's something proposed for CSS4, but you'd have to wait for that to actually be implemented in browsers. – MarcinJuraszek Dec 03 '15 at 00:54
  • Not a duplicate - this about first-of-type, the other question is about first-child, also first-of-type is supposed to be there in CSS3 – Chris Halcrow Dec 03 '15 at 02:21

1 Answers1

1

You're doing this correctly. According to the definition:

The :first-of-type selector in CSS allows you to target the first occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”

...and it should theoretically work in modern browsers. It works for me in the latest versions of Firefox, IE and Chrome

  • You're missing a closing </div> on the last line of your HTML sample - if this is also in your actual code, does fixing it help?
  • Is there another style rule somewhere that's overriding what you're trying to do? What happens if you change the rule to .text:first-of-type !important, which will force this rule to have higher priority?
  • Maybe if this is nested in other HTML you need to make the .text:first-of-type rule more specific? E.g. is the HTML nested within another element or class - in that case apply the rule by specifying that it applies to anything under that element or class e.g.

    div .text:first-of-type { color: red; }

Chris Halcrow
  • 28,994
  • 18
  • 176
  • 206
  • 1
    Unlikely for it to be the OP's actual markup. Based on their description, it's very likely there are other divs interfering with the selection. – BoltClock Dec 03 '15 at 02:34