1

I've found an odd bug where the CSS :first-child selector doesn't seem to be able to select a table row for me.

I have the following table

<table>
    <tr class="a">
        <td>a</td>
    </tr>
    <tr class="b">
        <td>b</td>
    </tr>
    <tr class="b">
        <td>b</td>
    </tr>
    <tr class="c">
        <td>c</td>
    </tr>
    <tr class="c">
        <td>c</td>
    </tr>
</table>

I want to add a row before the first instance of tr.b.

This code will not work:

$("table tr.b:first-child").before("<tr><td>using css selector</td></tr>");

but this will work fine:

$("table tr.b").first().before("<tr><td>using jquery first()</td></tr>");

Is this a known issue, or am I doing something wrong? I don't mind using jQuery but I don't understand why this isn't working with pure CSS.

Here's a fiddle of it:

http://jsfiddle.net/5d6YX/

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
roryok
  • 9,325
  • 17
  • 71
  • 138
  • 3
    it is how :first-child is support to work... it does not look for the first element matching a criteria... it always represents the first child of a parent element... in your case the `.b` element is not the first child of the parent `.a` is so `.b:fist-child` won't return anything – Arun P Johny Apr 04 '14 at 11:09
  • 1
    Are you looking for `$("table tr.b:first")`? – Satpal Apr 04 '14 at 11:10
  • your css selector `table tr.b:first-child` check if `tr:first-child` has claas `.b` . in your code the first `tr` child of table has class `.a`. the second tr is `nth-child(2)` .:) – G-Cyrillus Apr 04 '14 at 11:19
  • possible duplicate of [jQuery :first vs. .first()](http://stackoverflow.com/questions/2312761/jquery-first-vs-first) – Mr_Green Apr 04 '14 at 11:22
  • @Mr_Green: But this question is about `:first-child`, not `:first`. – BoltClock Apr 04 '14 at 11:46
  • @BoltClock oops yep.. sorry :) – Mr_Green Apr 04 '14 at 12:13

4 Answers4

1

That is how it suppose to work.The :first pseudo-class is equivalent to :eq(0). It could also be written as :lt(1). While this matches only a single element, :first-child can match more than one: One for each parent.

Try this:

$("table tr.b:first").before("<tr><td>css selector</td></tr>");

OR

$("table tr.b:eq(0)").before("<tr><td>css selector</td></tr>");

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

Just about CSS sibbling with selector.

In CSS , your selecteur would be :

table tr:first-child + tr.b

to only select the seconf row if it has class .b

to select the first .b class , you would need to overwrite the rule.

tr.b {/*set my rule */
tr.b ~tr.b {/*reset my rule */

It would be nice to have this kind of CSS selector avalaible : :first-of-class('myclass');

G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
0

Try this

$("table tr.b:first").before("<tr><td>css selector</td></tr>");

DEMO

Sridhar R
  • 20,190
  • 6
  • 38
  • 35
0

$("table tr.b:first") will do the trick.

Amit
  • 3,251
  • 3
  • 20
  • 31