Search code examples
javascripthtmlhtmlcollection

HTML collection structure same in all browsers


When you search elements using document.getElementsByTagName() we get a HTMLCollection. If elements have ids then output have elements with index and with id. enter image description here

Question is, will this structure remain constant across all browser or will it change?

Example

(function() {
  var inputs = document.getElementsByTagName("div")[0].children;
  console.log(inputs);
})()
<div id="content">
  <input type="text" id="input1" />
  <input type="text" id="input2" />
  <input type="text" id="input3" />
  <input type="text" id="input4" />
</div>


Solution

  • If more than one elements matching the string used as an index, you can't rely on browsers doing this equal.

    Browser compatibility
    Different browsers behave differently when there are more than one elements matching the string used as an index (or namedItem's argument). Firefox 8 behaves as specified in DOM 2 and DOM4, returning the first matching element. WebKit browsers and Internet Explorer in this case return another HTMLCollection and Opera returns a NodeList of all matching elements.

    Src: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection