Lothar
Lothar

Reputation: 3489

jQuery Selector - Children of children

I have the following jquery snippets (used with each to iterate over a table of results):

$('.foo').children('.bar').children('.first_baz').text();
$('.foo').children('.bar').children('.second_baz').text();

I use this to access $firstvalue and $secondvalue:

<tr class='foo'>
<td class='bar'><span class='first_baz'>".$firstvalue."</span><span class='second_baz'>".$secondvalue."</span></td>
</tr>

This works but is it efficient? I suspect there is a better way to access these values... what is it?

Upvotes: 1

Views: 2145

Answers (4)

ChrisThompson
ChrisThompson

Reputation: 2008

$('span.first_baz').text() 

if you don't need the parent structure, or

$('tr.foo > td.bar > span.first_baz').text()

if you do.

Upvotes: 0

Headshota
Headshota

Reputation: 21449

I haven't tried but this should be more efficient.

$('.foo .bar .first_baz').text();
$('.foo .bar .second_baz').text();

Upvotes: 1

Chandu
Chandu

Reputation: 82943

If the first_baz and second_baz elements are just with in the table and no where else in the page then you can skip the children function use the following snippet:

$('.first_baz').text(); 
$('.second_baz').text(); 

If the above case doesn't hold good then you can shorten the statements to

var parent = $('.foo'); //Get the parent context so that its not queried twice
$('.first_baz', parent).text(); 
$('.second_baz', parent).text(); 

Upvotes: 5

Dogbert
Dogbert

Reputation: 222428

You could cache all the .bar.

var bar = $('.foo').children('.bar')
bar.children('.first_baz').text();
bar.children('.second_baz').text();

Upvotes: 1

Related Questions