

Now, we can access the collections like we would an array:

HTMLCollection(4) 0: div.itemĪs you can see, this function has collected all of our elements with the item class together and output them into an array.

If we were to console log the items variable, we’d get the following output: Here’s how we collect them using getElementsB圜lassName:Ĭonst items = document.getElementsB圜lassName('item') This is the scenario: we have 4 divs with the same class and we want to collect them together to be able to access them. Using getElementsB圜lassName Javascript method to get an element by class In this scenario, the getElementsB圜lassName Javascript method is absolutely an acceptable way to do so. Or you could also use custom Data Attributes and use the querySelector Javascript method to access the element.īut what if you’re dealing with dynamic data? What if you don’t know how many elements there are? What if there could be one element or many elements and you need to anticipate that? If you know there will always be one identifier for one element, then it would be better to use the ID attribute to access the element with the getElementById Javascript method.
