Forum Moderators: open
<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.
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.
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>