querySelectorAll

giandodev

GiandoDev

Posted on May 6, 2020

querySelectorAll

Sometimes we need to select more than one item. We may select items through the tag name, the class, or a specific attribute.
Alt Text

        <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>
Enter fullscreen mode Exit fullscreen mode

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:

Alt Text
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.
Alt Text
More about querySelectorAll MDN
More about getElemntById MDN
More about getElementByClassName MDN

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
giandodev
GiandoDev

Posted on May 6, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About