Get the first element in the document with class="example":
document.querySelector(".example");
Click the button to add a background color to the first element in the document with class="example".
<!DOCTYPE html> <html> <body> <h2 class="example">A heading with class="example"</h2> <p class="example">A paragraph with class="example".</p> <button onclick="myFunction()">Test</button> <script> function myFunction() {//from w w w . ja va 2 s.com document.querySelector(".example").style.backgroundColor = "red"; } </script> </body> </html>
The querySelector()
method returns the first element that matches a specified CSS selector(s) in the document.
To get all the matches, use the querySelectorAll()
method.
document.querySelector(css-selector);
Parameter Values
Parameter | Type | Description |
---|---|---|
css-selectors | String | Required. Sets one or more CSS selectors to match the element. For multiple selectors, separate each selector with a comma. |
The querySelector()
method returns a NodeList object representing the first element that matches the specified CSS selector(s).
If no matches are found, null is returned.
It throws a SYNTAX_ERR exception if the specified selector(s) is invalid.