why document.getElementsByClassName(“className”) returns object

I have a some dom objects that are selected with :

 var elems = document.getElementsByClassName("royal") ;

and also another objects

var collapsedElems =  document.getElementsByClassName("collapsed");

my problem occured when i tried to concat elems and collapsedElems with array concat() method

 elems.concat(collapsedElems) 

but the return type of getElementsByClassName() is not array actually it is object. I checked it at chrome console with typeof operator. that seems weird to me how can i combine this two group of object. ?

Answers:

Answer

getElementsByClassName() returns an HTMLcollection object which is similar to an array but not really an array so you can't call array methods using the returned value.

One hack is to use Array's prorotype methods along with .call()/.apply() to pass the returned object as the context.

var elems = document.getElementsByClassName("royal") ;
var collapsedElems =  document.getElementsByClassName("collapsed");
var earray = Array.prototype.slice.call(elems, 0);
var concatenated = earray.concat.apply(earray, collapsedElems) ;
console.log(concatenated)

Demo: Fiddle

Answer

It returns an HTML Collection which does things that arrays do not (such as getting live updates when the DOM changes).

If you want to get an array with elements from both collections in it, then you could:

  • Create an array and then populate it by looping over each of the collections and pushing each member into it (which will give you an array) or
  • Use document.querySelectorAll(".royal, .collapsed"); (gets a NodeList)
Answer

From the MDN:

Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.

You can try this:

function getElementsByClassName(className) 
{
   if (document.getElementsByClassName) 
   { 
     return document.getElementsByClassName(className); 
   }
   else 
   { 
     return document.querySelectorAll('.' + className); 
   } 
 }

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.