The querySelector()
method returns the first child element that matches
a specified CSS selector(s) of an element.
querySelector |
Yes | 8.0 | Yes | Yes | Yes |
element.querySelector(CSS selectors)
Parameter | Type | Description |
---|---|---|
CSS selectors | String | Required. CSS selectors to match the element. |
The first element that matches the specified CSS selector(s).
The following code shows how to change the text of the first child element with class="example" in a <div> element.
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {<!-- w ww. j a v a 2s . co m-->
border: 1px solid black;
}
</style>
</head>
<body>
<div id="myDIV">
<h2 class="example">heading</h2>
<p class="example">paragraph</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 code above is rendered as follows: