1

I'm trying to hide the span element inside of the first .lineB element:

<div id="main">
    <div class="lineA">I'm LineA</div>
    <div class="lineA">I'm LineA</div>
    <div class="lineB">I'm the first LineB <span>DONT SHOW ME</span></div>
    <div class="lineB">I'm LineB</div>
    <div class="lineB">I'm LineB</div>
    <div class="lineA">I'm LineA</div>
</div>

I've tried:

#main .lineB:first-of-type span {display: none}

But this doesn't work. Any ideas why?

Fillip Peyton
  • 3,637
  • 2
  • 32
  • 60
  • possible duplicate of [CSS selector for first element with class](http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class) – Bijan Nov 04 '14 at 22:48
  • @Bijan - Not quite a duplicate. The answer supplied there does not solve my issue. – Fillip Peyton Nov 04 '14 at 22:55

2 Answers2

3

Perhaps applying for all, and negating for all but first will fit your case

.lineB{color:red}
.lineB ~ .lineB{color:inherit}
<div id="main">
    <div class="lineA">I'm LineA</div>
    <div class="lineA">I'm LineA</div>
    <div class="lineB">I'm the first LineB</div>
    <div class="lineB">I'm LineB</div>
    <div class="lineB">I'm LineB</div>
    <div class="lineA">I'm LineA</div>
</div>

In your specific example you could just use #main .lineB span{display:none} since you only have a span inside the first.

The :first-of-type works on the element type (the tag) so it would match only an element that is the first of its type (tag) under the parent. Since all of your elements are div the :first-of-type matches the first div.

Extending my initial answer to handle this scenario you can do

#main .lineB span{display:none}
#main .lineB ~ .lineB span{display:initial}
<div id="main">
    <div class="lineA">I'm LineA</div>
    <div class="lineA">I'm LineA</div>
    <div class="lineB">I'm the first <span>hide me</span> LineB</div>
    <div class="lineB">I'm LineB <span> show me</span></div>
    <div class="lineB">I'm LineB</div>
    <div class="lineA">I'm LineA</div>
</div>
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
1

In short: No. There is no : first-of-class selector. What you can do is:

  1. Use .lineA + .lineB to to select every element with the class "lineB" that follows an element with class "lineA".

or

  1. Use the .lineB:first-of-type selector and use a different element type for the two different classes (e.g. p and div).

or

  1. Of course, use JavaScript.
René Schubert
  • 1,302
  • 2
  • 13
  • 31