zsharp
zsharp

Reputation: 13766

How do I change the html element <li>'s color with a click via jQuery?

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.

Upvotes: 1

Views: 4693

Answers (2)

roborourke
roborourke

Reputation: 12217

// 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");
});

Upvotes: 5

Stephen Caldwell
Stephen Caldwell

Reputation: 5054

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

Upvotes: 1

Related Questions