Reputation: 22343
Using JQuery, how do I select all elements with class x within an element with id y?
Upvotes: 3
Views: 246
Reputation: 72222
$("#x .y").doSomething();
$(".y", "#x").doSomething();
$("#x").find(".y").doSomething();
And for immediate children:
$("#x > .y").doSomething();
$("#x").children(".y").doSomething();
Have a look at my question here, it tells you a bit more and it covers performance. What is the fastest method for selecting descendant elements in jQuery?
Upvotes: 4
Reputation: 513
Where you have element 1 with id='y' and you want all it's [immediate] children that have a class='x'
$("#y > .x").each(function(){stuff]);
If you want all decendants of id='y' (not just immediate) then you would do:
$("#y").find(".x").each(function(){stuff});
Obviously, you could make it smarter (and better) by adding element types if you know what they are. For example, if you want only children of type then:
$("#y > a.x").each(function(){stuff]);
Hope that's what you meant.
Upvotes: 1
Reputation: 184
$('#y .x')
should do it for you.
note that this will select all descendants with class x, not just children.
Upvotes: 5
Reputation: 17782
Selecting all descendants with class x of an element with the id "y".
$("#y .x").each(function () {
$(this) <- your element
});
Selecting all childrens with class x of an element with the id "y".
$("#y > .x").each(function () {
$(this) <- your element
});
Upvotes: 6