Question

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/

Était-ce utile?

La solution

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

Autres conseils

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');

Try this

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

DEMO

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top