Reputation: 6183
I want to select first elements of a class which are children of elements of another class using jQuery. Please have a look at an example below to understand my question.
<div class="a">
<div class="c"></div>
<div></div>
<div class="b">Select this</div>
<div class="b"></div>
<div class="b"></div>
</div>
<div class="a">
<div></div>
<div class="c"></div>
<div class="b">Select this</div>
<div class="b"></div>
<div class="b"></div>
</div>
<div class="a">
<div class="b">Select this</div>
<div class="b"></div>
<div class="b"></div>
<div></div>
<div class="c"></div>
</div>
I want to write a code in jQuery which will select all first elements of class b under all elements of class a.
If I use the following code in jQuery, it does not work:
$(".a div.b:first-child").html('Changed!!!!');
How can I select those divs, which I marked as "Select this" in the html?
Upvotes: 0
Views: 214
Reputation: 14123
This should work:
.a > .b:first-child, .a > :not(.b) + .b
Compared with nonstandard :first
pseudoclass supported by jQuery, this should work much faster in browsers that support querySelectorAll()
natively (IE9+).
Upvotes: 0
Reputation:
If you want to change the text in the tags that have 'Select this':
$('.a div').each(function()
{
if ( $(this).html() == 'Select this' )
$(this).html('changed');
});
Upvotes: 0
Reputation: 74410
Try this instead:
$(".a div.b:eq(0)").html('Changed!!!!');
// OR
$(".a div.b:first").html('Changed!!!!');
Upvotes: 0
Reputation: 79850
Use :first
instead of :first-child
and Also use .find
for specific sections. See below,
$(".a").find("div.b:first").html('Changed!!!!');
DEMO: http://jsfiddle.net/kjV5j/1/
Upvotes: 4