javascript - jQuery closest() appears to find parent id when there is none -


i have event listener when user clicks in window. want see if clicked element has parent element id. use jquery closest() function that. returns true.

here fiddle demonstrates code.

there must major error, because if change id if($(event.target).closest('#activatemenu')) other id

if($(event.target).closest('#rrrrrrr')) 

it still returns true.

code in fiddle:

$(function() {    	$(document).click(function(event) {        if($(event.target).closest('#activatemenu')) {     				                   $('.wrap').prepend('<p>the clicked element has parent id of activatemenu</p>');                 }else{                	   $('.wrap p').remove();                 }        });      });
.stuff{    width:300px;    height:150px;    border:red 2px solid;  }  .otherstuff{    width:400px;    height:400px;    background:purple;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>    <div class="wrap">    <div id="activatemenu">      <div>        <div>          <div class="stuff">             <p>here text</p>          </div>                 </div>      </div>    </div>    <div class="otherstuff">      <p>other stuff!</p>    </div>  </div>

you have 2 problems code.

  1. first, need search closest activemenu not activatemenu. activatemenu not exist in code.
  2. second, jquery return array need check length see whether element found non-empty array return true.

see below working example:

$(function() {      $(document).click(function(evt) {          if($(evt.target).closest('#activemenu').length) {              $('.wrap').prepend('<p>the clicked element has parent id of activemenu</p>');          } else {              $('.wrap p').remove();          }      });  });
.stuff {      width: 300px;      height: 150px;      border: red 2px solid;  }    .otherstuff {      width: 400px;      height: 400px;      background: purple;  }
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-bbhdlvqf/xty9gja0dq3hiwqf8lacrtxxzkrutelt44=" crossorigin="anonymous"></script>  <div class="wrap">      <div id="activemenu">          <div>              <div>                  <div class="stuff">                      <p>here text</p>                  </div>              </div>          </div>      </div>      <div class="otherstuff">          <p>other stuff!</p>      </div>  </div>


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -