Getting the ID of an element with plain JavaScript

I was searching for this for very long and didn’t really found something useful unless using a¬†JavaScript¬†framework, but for those who want to learn to code from scratch this is the answer.

First you have to get the element that triggers an event. example:


<div id="hello" onclick="getId();"></div>
<!-- in Firefox is necessary to include the event in the function -->
<div id="hello" onclick="getId(event);"></div>

In the HTML page header add the getId(e) function with: (note that I didn’t pass any value in the html code for any browser except Firefox)

function getId(e){
 var tgt;
 var id;
 if (!e) var e = window.event; // if e is undefined
 if ( tgt =; // For most browsers 
 else if (e.srcElement) tgt = e.srcElement; // For microsoft browsers 
 if (tgt.nodeType == 3) // To avoid webkit bug 
 tgt = tgt.parentNode; 
 id = tgt.getAttribute('id',2);

Every DOM event carry out the event information, you only has to targeted, and of course all mayor browser do it differently so you need to code so the right event is processed. Most browsers uses while Microsoft uses window.event.srcElement.

First the function try to locate the variable e value, because we didn’t provide it in the html e variable is undefined, so the function create the event, then try to assign the as the variable tgt value, if this doesn’t work, the creates the window.event.srcElement object as the variable value. If this failed, for Safari bug then it looks for the window.event.nodeType object and assigned it to the variable.

Once we have our object assign to the variable the function call for the getAttribute() element object. First you tell the attribute name you are targeting, in this case the id attribute. The second value 2 is to get exactly the value of the attribute. Another options are 0 that’s a default and perform a non-case sensitive search or 1 that perform a case-sensitive search of the value. I decided to use 2 because returns the property value as it is set in the script or html code.

That’s it. Nothing to it, I hope this help my fellow coders.

Thanks to

Happy Coding!

Leave a Reply