7

I've 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

4 Answers 4

9

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");
Sign up to request clarification or add additional context in comments.

3 Comments

I want to use what I have above, I just made the example easy to understand.
You trying to append a string to a jQuery object. It wont work!
$("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.
3

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.

2 Comments

How can I debug in FF to get NaN?
Well, I just run {} + 'a' in Firebug
2

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

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

Comments

0

try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.