Document querySelector() Method - Javascript DOM

Javascript examples for DOM:Document querySelector

Description

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 Values

Parameter Type Description
CSS selectors String Required.

Technical Details

Return Value:

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":

Demo Code

ResultView the demo in separate window

<!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>

Related Tutorials