views:

1095

answers:

4

Ive been trying to figure this one out for about 2 days and cant understand why this isn't working.

Say for example I declare a variable "ul" and want to say var + li display red.

$("document").ready(function()  { 

var menu = $("ul");

$(menu +" li").css("color","red");

});

All list items should now be red. What am I doing wrong?

Example: http://jsbin.com/izela

+2  A: 

To change all the direct children to red you can use

menu.children('li').css("color","red");

If you require all li's within the ul (nested ul>li>ul>li) then use .find

menu.find('li').css("color","red");

redsquare
I want to use what I have above, I just made the example easy to understand.
Bruno
Why when it is not the right way to do things?
redsquare
You trying to append a string to a jQuery object. It wont work!
redsquare
see http://jsbin.com/avune
redsquare
$("ul") is a jquery object - you can not "add" a string to it and get anything useful... You can do $("li", menu) or menu.children() or menu.find(). Or you could store var menuSlector = "ul" then $(menuSelector + " li") would work, but one of the options above would be much better.
gnarf
A: 

You should run something like this:

menu.children('li').css('color', 'red');

The problem is that menu is an object and adding string to an object return NaN (in FF) which cannot be used as a selector.

RaYell
How can I debug in FF to get NaN?
Bruno
Well, I just run `{} + 'a'` in Firebug
RaYell
A: 

What you're doing wrong is adding a jQuery object with a string. Try:

var menu = $('ul');
menu.find('li').css('color', 'red');
chaos
A: 

try

menu.children('li').css('color', 'red');
mkoryak