JavaScript for(x in element) strange results
Alright, I'm trying开发者_如何学Python 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: getElementsByTagName
returns a NodeList
, which has numeric indices and a length
property, thereby making it an Array
-like object.
Nevertheless, you should just use a simple for
loop like so:
var els = document.getElementsByTagName('div');
for(var i = 0, j = els.length; i < j; i++) {
alert(els[i].nodeName);
The reason why you want to use for
and not for..in
here is because for..in
uses inherited properties of the iterated object, so to avoid that you can use hasOwnProperty
, but in this case where you're only iterating over a numeric indice, I think it's better to use a simple for
loop over using for..in
and hasOwnProperty
.
Javascript returns all properties of the object when using for ( in ). Use .hasOwnProperty to skip inherited properties:
var elems = documents.getElementsByTagName('div');
for (x in elems){
if (elems.hasOwnProperty(x))
alert(elems[x].nodeName);
}
精彩评论