Get ID of element


#1

Hello All,

How can I get the ID of an element. I am aware that I can getElementById but I want to get the ID of an element.

For Instance:

<div id="content">
     <div id="*** dynamic ID ***">
     </div>
</div>

var firstDiv = document.getElementById("content").firstChild;

currently if I do alert(firstDiv) it will alert [object Text]. That confuses me a little too.

Thanks for any help


#2

Hi there matches,

does this help...

<font color='navy'>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript">
window.onload=function(){
   var obj=document.getElementById('content');
for(var c=0;c<obj.childNodes.length;c++){
if(obj.childNodes[c].nodeType==1) {
   alert(obj.childNodes[c].id);
   }
  }
 }
</script>

</head>
<body>

<div id="content">

<div id="*** dynamic ID ***"></div>

<div id="another id"></div>

</div>

</body>
</html>
</font>

coothead


#3

var firstDivID = document.getElementById("content").firstChild.id;

btw it's best not to use firstChild because it might unexpectantly return a text node (which is not what you want).

A better way would be to find the first element within the div. So if you're looking for a DIV within another DIV then:

var firstDivID = document.getElementById("content").getElementsByTagName('div')[0].id;

If you want to navigate the DOM using firstChild / childNodes[n] etc etc. then make sure when you use the referenced nodes, you check them first to make sure they're what you expected.

For example to make sure "firstChild" is a div:

var firstDiv = document.getElementById("content").firstChild;
if( firstDiv.nodeName.toLowerCase()==="div" ) {
   var firstDivID = firstDiv.id;
}


#4

Thanks for the tips JimmyP!


#5

I haven't tested it yet. But I think that is exactly what I was looking for.
Thanks!


#6

And if you're looking for the first element but you don't know what it might be, check the nodetype.
A value of 1 is an element, a value of 3 is a text node.

var firstEl = document.getElementById("content").firstChild;
while (firstEl.nodeType != 1) {
    firstEl = firstEl.nextSibling;
}


closed #7