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:

HTML

<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 (e.target) tgt = e.target; // 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);
 alert(id);
}

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 window.event.target 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 window.event.target 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
www.quirckmodes.com
www.roseindia.net

Happy Coding!

This entry was posted in Tutorials and tagged , , , , by Rafael Vila. Bookmark the permalink.

About Rafael Vila

I'm a Son of God, Father of three extremely awesome sons, husband of my sweetie pie Estella. I work as a Graphic Designer and a Web Developer in a Texan Company called Stealth Products, Inc. I've been blessed with a beautiful family and a great community of Faith. I believe God is the only God, who sent his son Jesus who become our Saviour and Redeemer Christ. The mercy and compassion of God is my daily wonder.