Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine which element has specific classname?

I have this HTML structure:

$("li").on("click", function(){ 
  // I need to remove active-class form current element
  $(this).addClass("active");
});
li:hover{
  background-color: #eee;
  cursor: pointer;
}

.active{
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Numbers:

<ul>
  <li>One</li>
  <li class="active">Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
</ul>

In the code above, when you click on the content of <li> tag, active class will be added to that element. Now I want to detect whether active class is on which element? and remove that class from it first (.removeClass()), and then add active class to clicked element. In other word, I need to make it (active class) unique.

How can I do that?

like image 225
stack Avatar asked Dec 15 '22 08:12

stack


1 Answers

Just use this:

$("li").on("click", function(){ 
  $('li.active').removeClass('active');
  // I need to remove active-class form current element
  $(this).addClass("active");
});

First remove the active class from previous active element: $('li.active').removeClass('active'), then simply update the clicked element.

like image 195
Dmitri Pavlutin Avatar answered Dec 17 '22 01:12

Dmitri Pavlutin