Using event.target to get an item

Basically I am trying to get the target element from event.target and, if not an equal process. How can I make it work below?

$(document).ready(function(){ $(document).click(function(event) { if(event.target!='#contents') { //If clicked element is not div #contents show alert .. //How can i achieve this ? alert(".."); } }); }); 
+8
jquery
source share
1 answer

using

  //If clicked element id is not contents if(event.target.id !== 'contents') { alert(".."); } 

EDIT - if the structure is used to use your comment:

  if($(event.target).closest('div#contents').length === 0){ alert('there is no div with id === "contents" in the ancestors of the clicked li'); } 

EDIT 2 is an explanation of my code. If you have this markup

 <div id="contents"><ul><li>Item1</li><li>Item2</li></ul></div> 

this code means

 //event.target is a DOM element, so wrap it into a jQuery object $(event.target) .closest('div#contents')//find a div element going up the dom tree. //This method returns a jQuery collection that it //empty if the div is not found .length //the collection has a length //property that is equal to the number of found elements 
+12
source share

All Articles