Hat
Hat

Reputation: 1731

how to get id of any element on click

Is it possible to have an alert pop up when any element on the page is clicked that tells you the tag name (or id or whatever other information) about that element? I basically want to set up the following for every element:

$('#wrapper').click(function() {
            alert($(this).prop('tagName'));
        })

Except I don't want to write that code for every single element on the page as that would take forever and would be extremely impractical in every way.

Upvotes: 0

Views: 202

Answers (4)

TT.li
TT.li

Reputation: 1

Here is an pure javascript method:

document.onclick = function(e) {
        e = e || window.event;
        var o = e.srcElement||e.target;
        alert(o.id);
    }

Upvotes: 0

adamdehaven
adamdehaven

Reputation: 5920

How about this

$(document).on('click', '*', function() {
    // Set clicked element's id to variable
    var elementName = $(this).attr('id');
    // Alert displaying id of clicked element
    alert(elementName);
})

Upvotes: 0

Shaz
Shaz

Reputation: 15867

document.body.addEventListener("click", function (e) {
       e = e || window.event;
       alert(e.toElement.getAttribute("id"));
});

Upvotes: 0

Loamhoof
Loamhoof

Reputation: 8293

Bind your listener on a global object with a selector.

$(document).on('click', '*', function() {
  alert($(this).prop('tagName'));
});

should work.

Upvotes: 1

Related Questions