0

I want to get the ID of an element that I click. It should only give me the ID if it has one.

I have this code to alert me the element ID:

$("[id]").click(function(event) {
    event.preventDefault();
    var id_name = $(this).attr("id");
    alert(id_name);
});

But I only want the foremost element's ID.

I have a button inside a div, both with an id-attribute. If I click the button, I only want the ID of the button. However, my script alerts me of both the buttons ID and the div's ID. Why is that/How can I get only the foremost element's ID?

Einar
  • 1,001
  • 3
  • 11
  • 28

3 Answers3

2

Thats because when you click the button, you are also clicking its parent element.

Add this within your function event.stopPropagation();

http://api.jquery.com/event.stoppropagation/

UserDy
  • 327
  • 5
  • 22
1

The problem is event propagation, Since you are targeting all elements you can bind the handler to the document object then check whether there is an id for the target element

$(document).click(function (event) {
    var id = event.target.id;
    if (!id) {
        return;
    }
    event.preventDefault();
    alert(id);
});
Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0
$("button[id]").click(function(event) {
   event.preventDefault();
   var id_name = $(this).attr("id");
   alert(id_name);
});

http://jsfiddle.net/asimshahiddIT/unm8qjzf/

asimshahiddIT
  • 330
  • 2
  • 5