What is the Class equivalent of document.getElementById() ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the Class equivalent of document.getElementById() ?

Is it document.getElementByClass(); for example?

12th Jul 2019, 9:48 PM
theAstarrr
theAstarrr - avatar
3 Answers
+ 1
Judah Thoreen Pick your choice 1. document.getElementsByClassName("cls") 2. document.querySelectorAll("[class*='cls']")
12th Jul 2019, 11:38 PM
Dlite
Dlite - avatar
+ 1
Close!! Its document.getElementsByClass(); ... element is pluralized. Hope this helps!
12th Jul 2019, 9:57 PM
Dezy R Nezzy
Dezy R Nezzy - avatar
+ 1
1. getElementsByClassName 2. It returns an HTMLCollection instead of a single element. Use number index to access each element, like handling an array. https://code.sololearn.com/WGAjaZ553jMG/?ref=app 3. querySelectorAll returns a NodeList NodeList is static, its length remain the same even though the elements are removed. On the other hand, HTMLCollection is dynamic, it kind of stores the query and execute the query everytime, so it's always updated and won't have undefined entry. https://code.sololearn.com/WMuGjuIx8O4s/?ref=app
13th Jul 2019, 12:51 AM
Gordon
Gordon - avatar