Forum Moderators: open

Message Too Old, No Replies

Printing IDs values

         

tkmoney

8:19 pm on May 19, 2005 (gmt 0)

10+ Year Member



Ok I have a html file like this :

<html>
<head>

<script type="text/javascript">

document.write(document.getElementsByName("unit").id)

</script>

</head>

<body>

<div id="1" name="unit">content</div>
<div id="2" name="unit">content</div>
<div id="3" name="unit">content</div>
<div id="4" name="unit">content</div>

</body>

</html>

Im just trying to print the id values. Its printing "undefined" right now. Im sure this is simple to do.

gph

10:45 pm on May 19, 2005 (gmt 0)

10+ Year Member



Here's what's wrong:

1/ Browsers read pages from the top down, the script is asking for page elements that don't yet exist.

2/ getElementsByName returns an array, you have to loop through the array to get individual element properties.

3/ look at the bottom of this [msdn.microsoft.com] page. A div can't have a name property.

What are you trying to achieve? There is probably a better way to do it.

tkmoney

10:49 pm on May 19, 2005 (gmt 0)

10+ Year Member



Im just want to list all of the id values on a page.

Bernard Marx

12:11 am on May 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Everything gph said, but twice.

Also, document.getElementsByName returns a collection of elements. This collection has no id property.

<!-- Must be last element in doc -->
<script type="text/javascript">
var output = [];
var elms = document.getElementsByTagName('*'); // * = all tagNames
for(var k=0;k<elms.length;k++)
if(elms[k].id)// if not empty string
output.push(elms[k].id);
document.write(output.join('\n'))
</script>
</html>