Junior
How to use a selector in CSS or JavaScript?
sobes.tech AI
Answer from AI
CSS selectors specify which HTML elements to style. In JavaScript, they are used to select DOM elements.
Main types of CSS selectors:
- Type selector: Selects all elements of a specified type.
div { /* styles for all <div> */ } - Class selector: Selects elements with a specified class.
.my-class { /* styles for elements with class "my-class" */ } - ID selector: Selects the element with a specified ID (must be unique).
#my-id { /* styles for element with ID "my-id" */ } - Universal selector: Selects all elements.
* { /* styles for all elements */ } - Combinators: Combine selectors.
- Descendant (
):div p- selects all<p>inside<div>. - Child (
>):div > p- selects all<p>that are direct children of<div>. - Adjacent sibling (
+):h2 + p- selects the first<p>immediately following<h2>. - General sibling (
~):h2 ~ p- selects all<p>following<h2>.
- Descendant (
In JavaScript, querySelector and querySelectorAll methods are used to select DOM elements.
querySelector: Returns the first element matching the specified CSS selector.// Selects the first element with class "my-class" const element = document.querySelector('.my-class');querySelectorAll: Returns a NodeList (array-like) of all elements matching the specified CSS selector.// Selects all <div> elements const elements = document.querySelectorAll('div');
Example of usage in JavaScript:
// Find button by ID
const myButton = document.querySelector('#my-button');
// Add click event handler
if (myButton) {
myButton.addEventListener('click', () => {
alert('Button clicked!');
});
}
// Find all list items with class "list-item"
const listItems = document.querySelectorAll('.list-item');
// Change text of each list item
listItems.forEach(item => {
item.textContent = 'Updated text';
});
The relationship between CSS selectors and their use in JavaScript querySelector/querySelectorAll is direct. You can use the same CSS selectors as in styles to select elements in JavaScript.