Capturing an element’s id with javascript click

Asked

Viewed 50,551 times

6

In the Document there are three <div>, all with the event onclick calling a function.

By clicking on any of the three, I would like to capture the id of the <div> clicked.

How can I capture the id of that element?

  • Smart implementation greatly decreases encoding

1 answer

17


If you are using Javascript inline (as in <div id="a" onclick="f()">...), does not. You would need to pass the id on the function call itself. But using JS inline is contraindicated, not only because of this but also because it is a mixture of structure (HTML) and behavior (JS).

If you are creating the Javascript event manager, just use this.id:

var div = document.getElementById('seuid');
div.onclick = function() {
    alert(this.id); // alerta 'seuid'
} 
// OU:
div.addEventListener('click', function() {
    alert(this.id); // alerta 'seuid'
});

Considering your comment that clarifies that this is a menu with several clickable items: delegate the treatment of the event for a higher element in the hierarchy, and get the clicked item of the event object that is automatically passed to the Systener. Example:

<ul id="fora">
    <li id="dentro1">aaaaaa</li>
    <li id="dentro2">aaaaaa</li>
    <li id="dentro3">aaaaaa</li>
</ul>
var el = document.getElementById('fora');
el.addEventListener('click', function(e) {
    alert(e.target.id);
});

http://jsfiddle.net/3Uuv5/

  • type, in your answer you set the object with getElementById(), but I don’t know which id the user will click, like, these three Divs would be menu items, and I wanted to apply an effect when this item was clicked, I have create an event for each one?

  • No, there’s a better way to do it in this case. See my update in reply.

  • Perfect, thank you very much. Just a doubt, in the new part of your answer where it gets specified that is to pick up the id of the interior elements?

  • 1

    The e is the such "event object" automatically passed. e.target is the element that triggered the event (the element clicked). e.target.id is the id of this guy. And this.id would be the id of ul, always.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.