tags:

views:

580

answers:

2

How to change the background color of UL 'li' on click?

EDIT i can change li "a" but what about the entire li

this works:

 $(".clickableUL").click(function() {
           $(this).find("li a").addClass("active");

       });

but find("li") does nothing. I want the LI highlighted not just the text of the link.

+3  A: 
// javascript
$("li>a").click(function(){
   $(this).parent().toggleClass("clicked");
});

/* CSS */
li { background: blue; }
li.clicked { background: red; }

You could also use display: block; on the <a> to make it fill the <li> unless you want it to stay changed.

EDIT: d'oh! just realised you could also apply the click event directly to the <li> itself eg.

$("li").click(function(){
   $(this).toggleClass("clicked");
});
sanchothefat
You might want to specify 'li > a' instead of plain 'a' for robustness.
strager
ah yeah, i just thought of that but forgot the single level bit. Thanks :)
sanchothefat
You forgot the >, or did you intend to omit that?
strager
i changed it to "li a" and forgot adding a > but you're right it's better practice to make selectors as non-leaky as possible
sanchothefat
A: 

You can modify the anchor's parent (assuming the parent is the <li> element.

$('a').click(function(evt) { 
   $(evt.target).parent().css('background-color', '#fff'); 
});
Stephen Caldwell