What is the thing instead of document.getElementById it's for a class? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is the thing instead of document.getElementById it's for a class?

Can you understand my question?😂😬

1st May 2022, 12:32 PM
Lego in Motion
Lego in Motion - avatar
2 Answers
+ 3
If you want to access class .blk elements For a single element class, you can use document.querySelector(".blk") to get the first element with class .blk For multi elements with the same class, you can use document.querySelectorAll(".blk") to get all the elements with class .blk (output in array elements) for example document.querySelectorAll(".blk")[0] would let you get the first element of all the .blk elements document.querySelectorAll(".blk")[1] would let you get the second element of all the .blk elements and so on... until the last element, document.querySelectorAll(".blk")[n-1] where n is total numbers of elements with class .blk Similarly for html tags, document.querySelectorAll("div") would get all the div tag elements document.querySelectorAll("h1") would get all the h1 tag elements It can also access #id element, with document.querySelector("#id) Since #id is an unique element in one document, you do not need to use method document.querySelectorAll
1st May 2022, 1:48 PM
Calviղ
Calviղ - avatar
+ 2
getElementsByClassName("class_name");
1st May 2022, 12:49 PM
Jayakrishna 🇮🇳