1

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.

1
  • Entire row? Can you show us some of your HTML, please? Commented Feb 3, 2009 at 1:10

2 Answers 2

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

4 Comments

You might want to specify 'li > a' instead of plain 'a' for robustness.
ah yeah, i just thought of that but forgot the single level bit. Thanks :)
You forgot the >, or did you intend to omit that?
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
1

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'); 
}); 

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.