Sometimes we need to select more than one item. We may select items through the tag name, the class, or a specific attribute.
<div className="fruits" data-fruits="I love fruits">🍉</div>
<div className="fruits" data-fruits="I love fruits">🍑</div>
<div className="fruits" data-fruits="I love fruits">🥭</div>
<div className="fruits" data-fruits="I love fruits">🍅</div>
<div className="fruits" data-fruits="I love fruits">🍈</div>
<div className="fruits" data-fruits="I love fruits">🍌</div>
<div className="fruits" data-fruits="I love fruits">🥑</div>
<div className="fruits" data-fruits="I love fruits">🍒</div>
querySelectorAll returns a nodelist that is an array-like, object—objects that looks like arrays. Array-like objects have length properties and have numbers as keys. In order to avoid problems, I suggest to always convert the nodelist in an array:
Now we may perform all the actions that an array allows us, like forEach method.
There are other methods that allow us to grab more than one items. They are getElementByClassName and getElementByTagName. This two methods are more fast than querySelectorAll method , but that is not a valid reason to use them.
The most important difference between getElementById, getElementByTagName and querySelectorAll is that querySelectAll is a static collection; this means that if you add or remove elements from the original selection your selection is not affected from this. On the other hand, with the other two methods the list is a live collection so if you change the original collection also your collection changes.
More about querySelectorAll MDN
More about getElemntById MDN
More about getElementByClassName MDN
Top comments (0)