Alright, I’m trying to use the basic document.getElementsByTagName function, but each time I do, it brings up results that don’t exist. Ie: elements with undefined nodeNames, and things like this. This causes my script to halt, and is giving me quite the trouble.
Here is a sample:
This HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<div></div>
<div></div>
<div></div>
</body>
</html>
with this script
for(x in document.getElementsByTagName('div'))
alert(document.getElementsByTagName('div')[x].nodeName);
generates this
DIV
DIV
DIV
undefined
then the script quits.
I cannot locate the issue, and it works like this in all browsers…
Just ask for any other details…
Correction:
getElementsByTagNamereturns aNodeList, which has numeric indices and alengthproperty, thereby making it anArray-like object.Nevertheless, you should just use a simple
forloop like so:The reason why you want to use
forand notfor..inhere is becausefor..inuses inherited properties of the iterated object, so to avoid that you can usehasOwnProperty, but in this case where you’re only iterating over a numeric indice, I think it’s better to use a simpleforloop over usingfor..inandhasOwnProperty.