How to retrieve this id value?

Hi,

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

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

I’m now getting ‘undefined’ as result. I can put the function inline, as in onclick=“alert('ID is: ’ + this.id)”, 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.

Use:

onclick="alert( this.id )"

-or-

onclick="showID( this )"

/* combined with */

function showID( elem)
{
  alert ( 'ID is: ' + elem.id );
}


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.

Cheers!

Ali,

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.