Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"closest()" is not working in else condition

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();
    }
});
like image 699
Rupesh Avatar asked Jun 02 '15 05:06

Rupesh


3 Answers

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

like image 162
Arun P Johny Avatar answered Nov 12 '22 06:11

Arun P Johny


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/

like image 30
Tharindu Kumara Avatar answered Nov 12 '22 07:11

Tharindu Kumara


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()
    }
});
like image 3
Zee Avatar answered Nov 12 '22 08:11

Zee