views:

28

answers:

4

I have an unordered list in an object:

var myUL = $('ul#theID'); //I send this var to another function in the code

I want the direct children only of this object (I have another 'ul' within each 'li' that also has 'li's in it), but this selector does not work:

$(myUL + '>li').each( etc, etc...

It gives me the error "uncaught exception: Syntax error, unrecognized expression: [object Object]" on this selector in Firebug.

If I use $('li', myUL) it gives me ALL of the 'li's withing the ul, not just the direct children, which is not what I want. I only want the direct children.

What is the correct syntax?

+1  A: 
$('>li', myUl)

That should be sufficient?

meder
That will probably work but it should be noted that Mr. Resig (and others) deprecate the use of the context argument, preferring `.find()`.
Pointy
I prefer `.find()` myself, actually because I don't need to go back if I've already typed `myUl`. People usually try to be more succinct in their answers, though and that's probably why I did it.. otherwise someone would have said "you can use a context".
meder
I don't think you're a bad person for using it, I just point it out because it's Official Dogma :-)
Pointy
+3  A: 

Try

var li_children = myUL.children('li');

(Properly, a <ul> can only have <li> children anyway.)

Pointy
+1  A: 
var myUL = Jquery('ul#theID');
jQuery('>li', myUL);


jQuery selector works this way
jQuery(selector, context);
Praveen Prasad
A: 

You need not use the tag name at the start of a selector that ends with an ID. ID alone is the fastest selector. Using a direct children method will be faster than a selector. Also not adding in a selector to the .children() method will allow jQuery to skip the filtering step that shouldn't be required as you should have all 'li' children regardless:

var $myUls = $( "#theID" ).children();

Cheers, awirick

Andrew Wirick