Question:

Explain how the document getElementsByClassName method works and give an example of its usage.


getElementsByClassName targets all the classes in the document and returns a live HtmlCollection list which is like an array but isn’t able to use it’s prototype methods like slice etc.

See the Pen getElementsByClassName by oscar (@nopity) on CodePen.

You can also chain commands to get classes from only certain sections like so.

var items = document.getElementsById('main').getElementsByClassName('items'); 
// this will get all class items that are children of the element with the id of main 

Or we can do something like this.

 var 2OfaKind = document.getElementsByClassName('alert green'); 
 // will collect all element that have both classes of alert and green