JavaScript selectors are used to select elements in HTML documents and operate on them. The following are commonly used JavaScript selectors:
-
getElementById:
Selects an element by its ID attribute and returns the first matching element.
-
getElementsByClassName:
Select elements by their class names and return an HTMLCollection containing all matching elements.
-
getElementsByTagName:
Select elements by their tag names and return an HTMLCollection containing all matching elements.
-
querySelector:
Select elements through the CSS selector and return the first matching element.
-
querySelectorAll:
Select elements through a CSS selector and return a NodeList containing all matching elements.
These selectors can be used flexibly as needed. For example, if you want to select the element with the ID "myElement", you can use getElementById("myElement"); if you want to select all elements with the class name "myClass", you can use getElementsByClassName("myClass"); if you want to select For all paragraph elements, you can use getElementsByTagName("p"); if you want to select the first element with a class name of "myClass", you can use querySelector(".myClass"), etc.
It should be noted that getElementById selects elements with a unique ID for the entire document, while other selectors can select multiple matching elements. In addition, HTMLCollection and NodeList are both array-like objects, and the elements in them can be traversed through indexing or looping.