Capture an element id with javascript click

5

In document there are three <div> , all with the onclick event that calls a function.

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

How can I capture the id of this element?

    
asked by anonymous 15.06.2014 / 04:58

1 answer

15

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

If you are creating the event listener by JavaScript, 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 it is a menu with multiple clickable items: delegate event handling to an element higher up in the hierarchy, and get the clicked item from the event object that is passed automatically to the listener. 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);
});

link

    
15.06.2014 / 05:02