Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does document["Some Name"] really do?

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?

like image 631
ILoveGit Avatar asked Dec 21 '22 14:12

ILoveGit


1 Answers

In JavaScript, object["string"] access the property 'string' on object. 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 the document object, this will get loaded with certain properties by default, like elements with the name attribute. At least for some browsers (I have no idea which subset).

That said, the name attribute isn't a valid attribute on an <h1> tag, so the document does not load that into document["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 same name attribute
  • <object>
  • <param> - Not the same name attribute
  • <select>
  • <textarea>

For each of these elements, if they have a name attribute, they will be added to the document, as you can see. The preferred way to get this elements, though, is using document.getElementsByName()

like image 168
LoveAndCoding Avatar answered Jan 09 '23 17:01

LoveAndCoding