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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With