Javascript Reference - HTML DOM querySelector() Method








The querySelector() method returns the first child element that matches a specified CSS selector(s) of an element.

Browser Support

querySelector Yes 8.0 Yes Yes Yes

Syntax

element.querySelector(CSS selectors)

Parameter Values

Parameter Type Description
CSS selectors String Required. CSS selectors to match the element.




Return Value

The first element that matches the specified CSS selector(s).

Example

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: