Element querySelector() Method - Javascript DOM

Javascript examples for DOM:Element querySelector

Description

The querySelector() method selects the first child element by CSS selector(s) of an element.

It throws a SYNTAX_ERR exception if the specified selector(s) is invalid.

Parameter Values

Parameter Type Description
CSS selectors String Required.

Return Value:

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

If no matches are found, null is returned.

The following code shows how to change the text of the first child element with class="example" in a <div> element:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {// w w w .  j a  va2  s  .  com
    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>

Related Tutorials