views:

80

answers:

3

is there another way to get an element's ID?

obj.getAttribute('id')
+4  A: 

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);
}
Nick Craver
and .id works with all html tags?
Rana
@Rana - Yup, it's a DOM element property, and all specific elements inherit from the basic dom element, so they have the property :)
Nick Craver
+1 nice one, learn something every day.
Tom
+1  A: 

This would work too:

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

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

michael
`getElementsByClassName` is not supported in IE (before IE9).
patrick dw
It was a mistake. Meant 'getElementByTagName' for dealing with a tag
michael
It's getElementsByTagName
I.devries
+2  A: 

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

Morteza Manavi