Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using event.target to get element

Tags:

jquery

I'm basically trying to get the target element from event.target and if not equal process. How can i get the below thing to work ?

$(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("..");
       }

    });
});
like image 776
user1184100 Avatar asked Apr 05 '12 09:04

user1184100


People also ask

Is event target an element?

target in JavaScript? When an event is fired, the element that fires the event is known as the emitter. This element is what we call the target.

Can I get an ID from event target?

You can use the event. target property to get the ID of the element that fired an event in jQuery. This property always refers to the element that triggered the event. The following example will display the name of the element that was just clicked.

How do you get a class from event target?

To check if event. target has specific class, call the classList. contains() method on the target object, e.g. event.

What is the use of event target value?

target gives you the element that triggered the event. So, event. target. value retrieves the value of that element (an input field, in your example).


1 Answers

use

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

EDIT - if the structure is that of your comment use:

  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 - 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's 
                                //empty if the div is not found
        .length //the collection has a length 
                //property that is equal to the number of found elements
like image 99
Nicola Peluchetti Avatar answered Sep 22 '22 17:09

Nicola Peluchetti