ray
ray

Reputation: 25

jquery :first selector loop problem

$(".wrap table tr:first").addClass("tr-top");

it works for the first table, but i have many tables under the div .wrap. what should i do? thanks!

Upvotes: 1

Views: 393

Answers (2)

user113716
user113716

Reputation: 322462

In your example, this line returns the first in the set of all tr elements found.

$(".wrap table tr:first").addClass("tr-top");  // First <tr> of all that are found

So if you have 3 table elements, it will only return the first tr from the first table, since that will be the first tr element matched.

If you want the first tr for each table, you need first-child:

$(".wrap table tr:first-child").addClass("tr-top");  // First <tr> for each <table>

...which will return each tr that is a first child of its parent.

http://api.jquery.com/first-selector/

http://api.jquery.com/first-child-selector/

Upvotes: 1

Catfish
Catfish

Reputation: 19284

This should work. The each loops through each table within .wrap.

$('.wrap table').each(function() {
    $('.wrap table tr:first').addClass('tr-top');
}};

http://api.jquery.com/each/

Upvotes: 0

Related Questions