views:

2231

answers:

3

It seems that this should be simple, but I'm having trouble figuring out how to construct a selector that will return only elements that are a direct child of a root node.

If, for example, I have a reference to a div (myDiv), and I want to select only images that are direct children of that div, the following doesn't work:

jQuery("div > img", myDiv);

The "div" in the selector doesn't seem to match the root of the context, only descendants, and without a selector that will give me the root, I can't use ">". Any other ideas on how to select a direct child of a context root?

+6  A: 

You shouldn't repeat the div tag:

jQuery("> img",myDiv);
Philippe Leybaert
cool. thought I tried that, but guess I didn't. Seems to work. Thanks!
morgancodes
+4  A: 

if mydiv is a reference to a jQuery object

mydiv.children("img")

else

$(mydiv).children("img")
jQuery(mydiv).children("img")
Jon Erickson
A: 

If you want only direct descendents, you want children.

jQuery(myDiv).children('img')

or, if it's a jquery object...

myDiv.children('img')

or, if not, you can also do...

jQuery('>img', myDiv)
altCognito