0

I have a number of elements with the same class like this:

<html>
<head><title>example</title>
<script type="text/javascript" src="jquery.js">
</head>
<body>
<ul>
  <li class="togglebutton">elem1</li>
  <li class="togglebutton">elem2</li>
  <li class="togglebutton selected">elem3</li>
  <li class="togglebutton">elem4</li>
</ul>
$(document).ready(function(){

});
</body>
</html>

The selected element has a different color from the other elements. When a user clicks on ANOTHER element, I want that element to have the selected class - and all other elements should no longer have the selected class. In other words, only one element can be selected at any time.

I think I have worked out the logic, but I am not sure how to implement it using jQuery.

basically my approach would be:

(When an item is selected):

  1. Select all items using selector "ul > li.togglebutton"
  2. remove class 'selected' from all of the items fetched in step 1
  3. add class 'selected' to the current element that was clicked on.

Is this logic correct, or is there a better way of going about it?

Also, how may I implement the above logic (assuming there is no better alternative), using jQuery?

1 Answer 1

2
$("ul li.togglebutton").click(function() {
     $("ul li.togglebutton").removeClass("selected");
     $(this).addClass("selected");
});

edit: jsfiddle: http://jsfiddle.net/XfN4s/

Sign up to request clarification or add additional context in comments.

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.