I have made simple functionality for select(add check) div on 1st click and 2nd click it will be remove, I have used "closest()" in else condition. Not getting.
Please help.
For code click here
JS:=
var selected = $('.demo-select');
selected.click(function() {
$(this).toggleClass('selected');
if ($('.demo-select').hasClass('selected')) {
//alert(1);
$(this).append('<p class="test">check</p>');
} else {
//alert(2);
$('.demo-select').closest('.test').remove();
}
});
Need to use find() as you are looking for a descendant element not an ancestor element(.closest() is used to find an ancestor element matching the passed selector).
$(this).find('.test').remove();
Demo: Fiddle
Here you need to use find() instead of closet()
find() : Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element
closet() : For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
var selected = $('.demo-select');
selected.click(function() {
$(this).toggleClass('selected');
if ($('.demo-select').hasClass('selected')) {
//alert(1);
$(this).append('<p class="test">check</p>');
} else {
//alert(2);
$(this).closest('.test').remove();
}
});
.demo-select {
border: 1px solid;
height: 200px;
width: 200px;
}
.test {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="demo-select"></div>
<div class="demo-select"></div>
<div class="demo-select"></div>
Demo: http://jsfiddle.net/tharindukumara/3b4forzd/
Use find()
to achieve this. As closest()
will traverse up through its ancestors in the DOM tree and not its decendents.
$('.demo-select').find('.test').remove(); //OR simply $(this).find('.test').remove()
Update
For multiple elements use $(this)
var selected = $('.demo-select');
selected.click(function() {
$(this).toggleClass('selected');
if ($(this).hasClass('selected')) { //HERE $(this)
//alert(1);
$(this).append('<p class="test">check</p>');
} else {
//alert(2);
$('this').find('.test').remove(); //HERE $(this) and find()
}
});
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