0

I know document.getElementsByName works differently in IE and Firefox, in IE, it returns HTMLCollection, while in Firefox, it returns NodeList.

In Firefox, the code is working correctly, while in IE, it always return length 0. The IE version is 11.

The code is:

var fullToken = document.getElementsByName("0");
console.log(fullToken.length);

  <span name ="0">h</span>
  <span name ="0">e</span>
  <span name ="0">l</span>
  <span name ="0">l</span>
  <span name ="0">o</span>
typeof programmer
  • 1,509
  • 4
  • 22
  • 34

1 Answers1

2

Your HTML is invalid. The span element cannot have a name attribute.

Internet Explorer appears to be ignoring the name attribute on elements where it is forbidden. If you change a span to an input it will show up in the list.

If you want to describe a group of elements for referencing with JavaScript, use a class with getElementByClassName.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • But the example documentation here : https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName#Example shows a div with `name` attribute... Isn't the span must be treated as a div – Zakaria Acharki Oct 03 '18 at 14:59
  • Why span cannot have name attribute? – typeof programmer Oct 03 '18 at 14:59
  • @ZakariaAcharki — The example MDN gives is invalid. https://validator.w3.org/nu reports "Error: Attribute name not allowed on element div at this point." – Quentin Oct 03 '18 at 15:02
  • @connexo — Not in Internet Explorer, and the code in the question demonstrates. – Quentin Oct 03 '18 at 15:03
  • @typeofprogrammer — In the bad old days, `name` was massively overloaded and used for all sorts of things. As HTML was standardised, those various functions were split out and shared between `name`, `id` and `class`. The primary function of `name` is to provide a key to be associated with data entered into a form control when that form is submitted. A span is not a form control. – Quentin Oct 03 '18 at 15:04
  • @connexo MSDN (I don't know if this is still relevant, but it matches the behavior): _"When you use the `getElementsByName` method, all elements in the document that have the specified `NAME` attribute or `ID` attribute value are returned. Elements that support both the `NAME` attribute and the `ID` attribute are included in the collection returned by the `getElementsByName` method, **but elements with a `NAME` expando are not included in the collection**; therefore, this method cannot be used to retrieve custom tags by name"_ ([Src](https://msdn.microsoft.com/en-us/windows/ms536438(v=vs.71))) – Andreas Oct 03 '18 at 15:20
  • @Quentin you are right, it's working now if I change the name attribute to class. Thanks a lot. – typeof programmer Oct 03 '18 at 15:30