Dim
Dim

Reputation: 3

Get <div> name using jQuery

$("body").click(function() {
       var item = "<h1>You clicked on: #" + $(this).attr('id');
       $(".position").html(item);
     });

Why is this giving me a blank response? I want it to identify each HTML object's ID clicked.

Upvotes: 0

Views: 2975

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69915

Try this

$("body").click(function(e) {
       var item = "<h1>You clicked on: #" + $(e.target).attr('id') + "</h1>";
       $(".position").html(item);
     });

Upvotes: 4

SLaks
SLaks

Reputation: 888293

this refers the the object that you registered the handler with, not the original source of the event.
In your case, this is always the <body>.

You want e.target, which refers to the element that directly triggered the event.
(where e is the first argument of the handler function)

Upvotes: 3

Related Questions