How can i select all elements by class name (in javascript) | SoloLearn: Learn to code for FREE!

+1

How can i select all elements by class name (in javascript)

Or: I can select with "jquery" an element with a class name assign it to a variable and get the position in the document example (in javascript with id): document.getElementById (""). style.top I want to do this same but with all the elements of a class

1/23/2021 2:14:42 AM

JoseD

13 Answers

New Answer

+5

there's two ways, each one returning a dynamic element list: document.getElementByClassName('targeted-class') or document.querySelectorAll('.targeted-class') note that second one get a css queryselector string (so here's a leading dot before class name), while first one take only one class name. Also, each one is also available on all html element ;)

+3

Futher from the answer from visph, I would like to show an example of using document.getElementsByClassName or document.querySelectorAll, so that JoseD can understand the iteration of these array-like object. https://code.sololearn.com/W60Pmu3zPn60/?ref=app

+2

Calviղ for (var blk of blks) also works, as well as any array method, as soon as you call it with the array made from dynamic list (es6: [...blks])

+2

https://code.sololearn.com/WBaAG7tcSZAR/?ref=app

+2

oh yeah: that's the only one 'map' method natively supported ^^

+2

I was mentionning it in my first comment after your first one ;)

+1

visph I changed the code now. Thanks for showing the more simple way.

+1

visph however I can't use array method, map method, any reason why?

+1

not directly on blks object, but you could 'slice' it to convert to array (es6 shortest way : [...blks].forEach())

+1

https://code.sololearn.com/WuX6D4EFo263/?ref=app

+1

I see, it need to convert to real array type first.

+1

However it works on forEach directly https://code.sololearn.com/WscqBRNU7aIx/?ref=app

+1

visph thanks for showing the spread operator method, it's useful. 👍