Object notation for DOM elements
In following example, there is array-like object for DOM elements and there is one thing which is unclear to me.
&l开发者_开发问答t;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
window.onload = function(){
for(var prop in document.links){
alert(prop); // It does not alert foo!
}
}
</script>
</head>
<body>
<a name="foo" href="#">foo</a>
</body>
</html>
In theory object notation for accessing prop is like: obj.prop
.
In object array-like there must be number notation for elements of a object: obj[0]
, and obj.length
.
And alert is giving: 0
, length
, item
, namedItem
. First two is from theory of object array-like and other two can be used for accessing props.
And, finally, this link could be found like document.links[0]
and document.links.foo
. There is no foo
prop in document.links
. Why? Thanks.
The reason document.links.foo
is not available is because you're using name
and not id
. If you change your markup to:
<a id="foo" href="#">foo</a>
Then this will work:
window.onload = function(){
window.alert(document.links.foo.innerHTML);
}
You're passing the DOM element itself to "alert()". What about passing the "name" attribute?
for(var prop in document.links){
alert(prop.name);
}
Now, it's really a bad idea to iterate through a node list like that:
for (var i = 0; i < document.links.length; ++i)
alert(document.links[i].name);
If you want the text content of the node, then you can try this:
for (var i = 0; i < document.links.length; ++i)
alert(document.links[i].innerHTML);
You could also find its child text nodes and extract their value.
Note that the "links" object will also include <area>
tags, if you've got any.
精彩评论