Mike Webb
Mike Webb

Reputation: 9003

How do I use jQuery selectors with an object?

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?

Upvotes: 0

Views: 74

Answers (4)

Andrew Wirick
Andrew Wirick

Reputation: 184

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

Upvotes: 0

Praveen Prasad
Praveen Prasad

Reputation: 32107

var myUL = Jquery('ul#theID');
jQuery('>li', myUL);


jQuery selector works this way
jQuery(selector, context);

Upvotes: 1

Pointy
Pointy

Reputation: 413737

Try

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

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

Upvotes: 3

meder omuraliev
meder omuraliev

Reputation: 186562

$('>li', myUl)

That should be sufficient?

Upvotes: 1

Related Questions