Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only the clicked element in JQuery [duplicate]

Tags:

jquery

How to get only the clicked element in JQuery

Suppose the following

<html>
  <body>
    <div>
      <h1>headding</h1>
    </div>
    <a>link</a>
  </body>
</html>

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

I need when click on h1 the alert show h1 and when click on a the alert show a etc.

The problem is when i click on any element the code make loop to show name of all parents element of the clicked element. but i need only the first clicked element. any help

like image 478
Eyad Farra Avatar asked May 07 '13 14:05

Eyad Farra


1 Answers

use stopPropagation() so the event doesn't bubble up

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

FIDDLE

like image 75
wirey00 Avatar answered Nov 15 '22 23:11

wirey00