Javascript examples for DOM:Document querySelector
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 instead.
It throws a SYNTAX_ERR exception if the specified selector(s) is invalid.
Parameter | Type | Description |
---|---|---|
CSS selectors | String | Required. |
A NodeList object. If no matches are found, null is returned.
The following code shows how to Get 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() {// w w w.j a v a 2s . c o m document.querySelector(".example").style.backgroundColor = "red"; } </script> </body> </html>