querySelectorAll
GiandoDev
Posted on May 6, 2020
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
Posted on May 6, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.