views:

84

answers:

5

Using JQuery, how do I select all elements with class x within an element with id y?

+5  A: 

$('#y .x') should do it for you.

note that this will select all descendants with class x, not just children.

Andrew Wirick
+1 for descendants vs. childrens
lasseespeholt
+1 for brevity (Ironic that I can't just put that as a comment: "Comments must be at least 15 characters in length.")
Homer
+6  A: 

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
});
lasseespeholt
The first code is the same as `$("#y").find(".x")` and the second is the same as `$("#y").find("> .x")`
BrunoLM
@BrunoLM +1 Good addition, I prefer my method, though. Also, if he wants to do ex `.click` instead, then `.each` is removed anyway.
lasseespeholt
+2  A: 

Use $("#id .class")

John Drummond
+4  A: 
$("#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. http://stackoverflow.com/questions/3177763/whats-the-fastest-method-for-selecting-descendant-elements-in-jquery

Marko
+1 - Thorough answer. Just thought I'd point out that in your second example, you don't need to pass a jQuery object for the context. You could just pass the string `"#x"`. jQuery flips it around into your third version behind the scenes. :o)
patrick dw
Ha! I was actually wondering about that. Thanks @patrick !
Marko
+1  A: 

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.

patrickgamer
Using `.children()` doesn't give you all descendants. Just immediate. You're thinking of `.find()`, which will return all matching descendants.
patrick dw
woops - my bad. I'll edit
patrickgamer