Is there another way to get an DOM element's ID?

element.getAttribute('id') 

8 Answers

Yes you can just use the .id property of the dom element, for example:

myDOMElement.id 

Or, something like this:

var inputs = document.getElementsByTagName("input"); for (var i = 0; i < inputs.length; i++) { alert(inputs[i].id); } 
2

Yes you can simply say:

 function getID(oObject) { var id = oObject.id; alert("This object's ID attribute is set to \"" + id + "\"."); } 

Check this out: ID Attribute | id Property

This would work too:

document.getElementsByTagName('p')[0].id 

(If element where the 1st paragraph in your document)

2

Super Easy Way is

 $('.CheckBxMSG').each(function () { var ChkBxMsgId; ChkBxMsgId = $(this).attr('id'); alert(ChkBxMsgId); }); 

Tell me if this helps

0

In events handler you can get id as follows

function show(btn) { console.log('Button id:',btn.id); }
<button onclick="show(this)">Click me</button>

This gets and alerts the id of the element with the id "ele".

var id = document.getElementById("ele").id; alert("ID: " + id); 
2

You need to check if is a string to avoid getting a child element

var getIdFromDomObj = function(domObj){ var id = domObj.id; return typeof id === 'string' ? id : false; }; 

Yes. You can get an element by its ID by calling document.getElementById. It will return an element node if found, and null otherwise:

var x = document.getElementById("elementid"); // Get the element with x.style.color = "green"; // Change the color of the element 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy