How I get active class only on click div not on all div??
html code
<div >
<div id="test-1"></div>
</div>
<div >
<div id="test-2"></div>
</div>
<div >
<div id="test-3"></div>
</div>
Jquery code
// adding this div for each place class
$('.place').wrap('<div.></div>')
//cut icon for hide
$('<i .place")
$(".removeBtn").on("click",function(){
$(".main__place").addClass("active")
})`
CodePudding user response:
In the following snippet I remove the clicked element by "looking up" to the closest .col-12
element:
// adding this div for each place class
$('.place').wrap('<div.></div>').prepend('<i ></i>')
$("body").on("click",".removeBtn",function(){
$(this).closest(".col-12").remove()
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<div id="test-1">1</div>
</div>
<div >
<div id="test-2">2</div>
</div>
<div >
<div id="test-3">3</div>
</div>
If you just want to toggle a class then you can just do that too:
// adding this div for each place class
$('.place').wrap('<div.></div>').prepend('<i ></i>')
$("body").on("click",".removeBtn",function(){
let curr=this.closest(".col-12");
$(".col-12").each(function(){$(this).toggleClass("active",this==curr)})
})
.active {background-color:red}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<div id="test-1">1</div>
</div>
<div >
<div id="test-2">2</div>
</div>
<div >
<div id="test-3">3</div>
</div>
CodePudding user response:
Could you try this :
I have added an x
to the remove button, you can remove it since you will have no problem with the fa
icons.
$('.place').wrap('<div ></div>')
//cut icon for hide
$('<i >x</i>').insertBefore(".place")
$(".removeBtn").on("click",function(){
$('.main__place').removeClass('active');
$(this).parent().addClass("active")
})
.active {background-color:#ccc}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<div id="test-1">test-1</div>
</div>
<div >
<div id="test-2">test-2</div>
</div>
<div >
<div id="test-3">test-3</div>
</div>