How to get the element clicked (for the whole document)?

user1145216 picture user1145216 · Jan 26, 2012 · Viewed 301.3k times · Source

I would like to get the current element (whatever element that is) in an HTML document that I clicked. I am using:

$(document).click(function () {
    alert($(this).text());
});

But very strangely, I get the text of the whole(!) document, not the clicked element.

How to get only the element I clicked on?

Example

<body>
    <div class="myclass">test</div>
    <p>asdfasfasf</p>
</body>

If I click on the "test" text, I would like to be able to read the attribute with $(this).attr("myclass") in jQuery.

Answer

alex picture alex · Jan 26, 2012

You need to use the event.target which is the element which originally triggered the event. The this in your example code refers to document.

In jQuery, that's...

$(document).click(function(event) {
    var text = $(event.target).text();
});

Without jQuery...

document.addEventListener('click', function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement,
        text = target.textContent || target.innerText;   
}, false);

Also, ensure if you need to support < IE9 that you use attachEvent() instead of addEventListener().