How to change class using jquery
MY JQuery Code:
$('a#cusine1').on('click', function(){
$('div#product-list').html("LOADING..........").show();
$(".ccid").addClass("0");
document.getElementById("ccid1").className="active2";
});
$('a#cusine2').on('click', function(){
$('div#product-list').html("LOADING..........").show();
$(".ccid").addClass("0");
document.getElementById("ccid2").className="active2";
});
$('a#cusine3').on('click', function(){
$('div#product-list').html("LOADING..........").show();
$(".ccid").addClass("");
document.getElementById("ccid3").className="active2";
});
MY HTML CODE
<li id="ccid1" class="ccid">
<a href="#" id="cusine1"><i class="fa fa-ticket"></i>3 Star Hotel</a> </li>
<li id="ccid2" class="ccid">
<a href="#" id="cusine2"><i class="fa fa-ticket"></i>3 Star Hotel</a> </li>
<li id="ccid3" class="ccid">
<a href="#" id= "cusine3"><i class="fa fa-ticket"></i>5 Star Hotel</a>
</li>
REQUIRED OUTPUTS:
I need to, when the button is pressed li
id " ccid1 ", should be added to the class of " Active2 ". the other li
should only have the ccid class .
The number li
may vary depending on PHP.
PROBLEM FOUND
First time clicking li
id " ccid1 " added class " active2 ". Then if li
id " ccid2 " is added, class active2 is added , but li
id " ccid1 " class is not set to " 0 ".
As I said in my comment, don't use class names that start with / only - Number.
That's all you need:
$('.ccid a').on('click', function(){ // This targets all your links
$('div#product-list').html("LOADING..........").show();
$(".active2").removeClass("active2"); // Remove existent active classes
$(this).parent(".ccid").addClass("active2"); // Set active class
});
source to share
The css class name cannot start with a number ( CSS grammar ) and any element can have more than a class, so if you need to remove the class (or set it to none) you must use removeClass
source to share
I'm making a little guesswork about what you need and this code is untested:
$('li.ccid').on('click', function(){
$(".ccid").removeClass("active2");
$(this).addClass("active2");
});
So, when clicking any li with the ccid class:
- We guarantee that the class "active2" is removed from all such li
- The class "active2" is added to the one that was clicked
source to share