This code
<img name="n1" src="" />
<h1 name="n2">a header</h1>
<script>
document["n1"].src = "http://x.y/picture.jpg";
document["n2"].innerHTML = "Boo";
</script>
Does something different for the <img> and <h1> tags. The picture src is changed as expected by the document["n1"].src line. But the heading innerHTML is not changed as expected by the document["n2"].innerHTML line. What does document["some string"] really return?
In JavaScript,
object["string"]access the property'string'onobject. This can be used to access many different properties on many different objects, and is like treating the object as a hash map of values. For thedocumentobject, this will get loaded with certain properties by default, like elements with thenameattribute. At least for some browsers (I have no idea which subset).That said, the
nameattribute isn’t a valid attribute on an<h1>tag, so the document does not load that intodocument["name"]value.The name attribute is valid on the following elements:
<a>– Attribute deprecated in HTML 4, obsolete in HTML5<applet>– Element obsolete in HTML5<button><form>– Attribute deprecated in HTML 4, returned in HTML5<frame>– Element obsolete in HTML5<iframe><img>– Attribute deprecated in HTML 4, obsolete in HTML5<input><map><meta>– Not the samenameattribute<object><param>– Not the samenameattribute<select><textarea>For each of these elements, if they have a
nameattribute, they will be added to the document, as you can see. The preferred way to get this elements, though, is usingdocument.getElementsByName()