To change a <div>
s text color from black to red with JavaScript, you first need to select <div
element using the
querySelector
method.
The document.querySelector
method lets you select an element using CSS-Style selectors:
- To select by id, prepend with
#
. - To select by class, prepend with
.
. - To select by tag, just write the tag name.
- To select by attribute, use square brackets
[]
.
Example:
querySelector
returns the first matching element. For multiple elements, use querySelectorAll
.
You can also use element.querySelector
to search within a specific element, which is faster than searching the
entire DOM.
Example:
Summary
- Use
document.querySelector
to select elements with CSS selectors. querySelector
returns the first match; usequerySelectorAll
for multiple elements.- Use
element.querySelector
to search within a specific element for better performance.