How to retrieve this id value?


How do I get the id value of the header into the alert in the next example:

<!DOCTYPE html>
function showID() {
    //return this; doesn't work
    ID =;
    alert ('ID is: ' + ID);
<h6 id="header" onclick="showID()">Header</h6>

I’m now getting ‘undefined’ as result. I can put the function inline, as in onclick=“alert('ID is: ’ +”, but I need it to work the other way.

Thanx in advance.

When you attach an event handler inline, i.e.: onclick=“showID()”, within the function this refers to window.


onclick="alert( )"


onclick="showID( this )"

/* combined with */

function showID( elem)
  alert ( 'ID is: ' + );

or attach the handler properly:

document.getElementById( 'header' ).onclick = showID; /* Ensure element has been rendered at this point.*/

Thanks, Ali! Not only for the solution, but also for explaining which mistake I made.

The second method you gave is the right one for this job.



You might be interested in what I needed it for. The answer is: a super simpel and super short javascript with which one can turn a normal multi-level CSS menu in one that also works on touchscreen devices (on which there is no hovering)… :slight_smile: Check it out and let me know what you think of it: link.