How to get only clicked item in jQuery

How to get only clicked item in jQuery

Assume that <

<html> <body> <div> <h1>headding</h1> </div> <a>link</a> </body> </html> $("*").click(function(e){ e.preventDefault(); alert($(this)[0].tagName); }); 

I need it when I click on h1 show h1 notification and when you press a , a warning a appears, etc.

The problem is when I click on any element of the make make code to display the name of all the parent elements of the clicked element. but I need only the first element. any help

+4
source share
4 answers

use stopPropagation () to prevent the event from bubbling

 $("*").click(function(e){ e.preventDefault(); e.stopPropagation(); alert($(this)[0].tagName); }); 

Fiddle

+7
source

You need to return false at the end to prevent the bubble.

 $("*").click(function (e) { e.preventDefault(); alert($(this)[0].tagName); return false; }); 

Tick fiddle

+4
source

You are using event propagation. The event comes from the element that you clicked on, but then propagates to the DOM tree in the root (document). You can use the stopPropagation method to prevent this, or return false from the event handler function (to prevent the default behavior and ):

  $("*").click(function(e){ e.preventDefault(); e.stopPropagation(); alert(this.tagName); }); 

or

 $("*").click(function(e){ alert(this.tagName); return false; //both prevents default and stops propagation }); 

Aside, $(this)[0] is nonsense. You create an array type object containing this , and then return the first element ( this ), so unnecessary function calls and access to the array get what you already have a direct reference to. Net overhead for zero gain, just use this directly.

+3
source

Just change the jQuery selector to add a click event for h1 and a :

 $("h1,a").click(function(e){ e.preventDefault(); alert($(this)[0].tagName); }); 
+1
source

Source: https://habr.com/ru/post/1479555/


All Articles