Change the text of the first child element with class="example" in a <div> element:
Click the button to change the text of the first element with class="example" in div.
<!DOCTYPE html> <html> <head> <style> #myDIV {/*from w w w. j av a 2 s . c o m*/ border: 1px solid black; } </style> </head> <body> <div id="myDIV"> <h2 class="example">A heading with class="example" in div</h2> <p class="example">A paragraph with class="example" in div.</p> </div> <button onclick="myFunction()">Test</button> <script> function myFunction() { var x = document.getElementById("myDIV"); x.querySelector(".example").innerHTML = "Hello World!"; } </script> </body> </html>
The querySelector()
method returns the first child element that matches a CSS selector(s).
The querySelector()
method only returns the first element that matches the specified selectors.
To return all the matches, use the querySelectorAll()
method instead.
element.querySelector(CSS-selectors);
Parameter Values
Parameter | Type | Description |
---|---|---|
CSS-selectors | String | Required. Specifies one or more CSS selectors to match the element. |
For multiple selectors, separate each selector with a comma.
The returned element depends on which element that is first found in the document.
If no matches are found, null is returned.
The querySelector()
throws a SYNTAX_ERR exception if the specified selector(s) is invalid.