+ 1

When do we use querySelector() and why.

4th Jan 2019, 1:20 AM
Juan David Padilla Diaz
Juan David Padilla Diaz - avatar
4 ответов
+ 4
It can be used for the same purpose we use to select elements for style with CSS. For example you can call an element with an id called 1 as #1 in the querySelector and then do something to it.
4th Jan 2019, 10:36 AM
Seniru
Seniru - avatar
+ 1
To select the FIRST matched tag, class or ID attribute from the html document. The selected element can be further updated by using its built in methods, eg innerText, innerHTML. To select all the identical tag or class, you could use querySelectorAll function.
4th Jan 2019, 2:46 AM
Calviղ
Calviղ - avatar
+ 1
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, 2:08 PM
Calviղ
Calviղ - avatar