HTML "name" attribute, Firefox misbehaves

It's been a long time since I wrote something about web-dev, that's because I code less web-stuff recently 🙂

"id" vs. "name" attributes

so far, I thought that "id" should be used for unique IDs, and "name" can be used for non-unique names, i.e. multiple HTML tags with the same name. I've been using document.getElementsByName(str) to get an array of elements with the same name.

Today I've figured out that it's only partially legal: the name attribute can be used only for specific elements (such as INPUT), but cannot be used on many elements (such as DIV). For some reason, Firefox accepts the name tag for any HTML element, while IE follows HTML 4.01 and doesn't accept name tags for "illegal" HTML tags.

Proof of concept

The next piece of JS/HTML code, gives different results on both browsers:

<div name="foo">bla</div>
<script type="text/javascript">
alert(document.getElementsByName("foo").length)
</script>

Results:

  • Firefox 3: 1
  • IE 7: 0

Here is a nice explanation with a full list of "name"-allowed HTML tags.

Leave a Reply

Your email address will not be published. Required fields are marked *