What kind of selectors can be used with querySelectorAll()?
Answers:
The
querySelectorAll()method allows you to select elements in the DOM using CSS selectors. It accepts a string parameter that specifies a group of CSS selectors, and will return all elements that match any of those selectors. Here are some types of selectors you can use withquerySelectorAll():-
Universal Selector:
*: Selects all elements.
const allElements = document.querySelectorAll('*'); -
Type Selector:
element: Selects all elements of a specific type (tag name).
const divs = document.querySelectorAll('div'); -
Class Selector:
.className: Selects all elements with a specific class.
const items = document.querySelectorAll('.my-class'); -
ID Selector:
#idName: Selects an element with a specific ID (note that IDs should be unique).
const header = document.querySelectorAll('#my-id'); -
Attribute Selector:
[attribute]: Selects elements with a specific attribute.[attribute="value"]: Selects elements with a specific attribute value.
const inputs = document.querySelectorAll('input[type="text"]'); -
Descendant Selector:
ancestor descendant: Selects elements that are descendants of a specified ancestor.
const listItems = document.querySelectorAll('ul li'); -
Child Selector:
parent > child: Selects elements that are direct children of a specified parent.
const directChildren = document.querySelectorAll('div > p'); -
Adjacent Sibling Selector:
previous + next: Selects an element that is directly after a specified element.
const nextElement = document.querySelectorAll('h1 + p'); -
General Sibling Selector:
previous ~ siblings: Selects all siblings of a specified element.
const siblings = document.querySelectorAll('h1 ~ p'); -
Pseudo-classes:
:hover,:nth-child(n),:last-child, etc.
const secondItems = document.querySelectorAll('li:nth-child(2)'); -
Pseudo-elements:
::before,::after, etc. (Note: pseudo-elements might not work as expected withquerySelectorAll()).
const beforeElement = document.querySelectorAll('p::before'); // Usually doesn't work directly
You can also combine selectors and use groups with commas:
const elements = document.querySelectorAll('div, .my-class, #my-id');These selectors allow for flexible and powerful ways to traverse and manipulate the DOM based on specific criteria.
-