Javascript Reference - HTML DOM querySelector() Method








The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.

Browser Support

querySelector Yes 8.0 Yes Yes Yes

Syntax

document.querySelector(CSS selectors)

Parameter Values

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




Technical Details

DOM Version: Selectors Level 1 Document Object
Return Value: A NodeList object, representing the first element that matches the specified CSS selector(s).

Example

The following code shows how to get the first element in the document with class="example":


<!DOCTYPE html>
<html>
<body>
<h2 class="example">A heading </h2>
<p class="example">A paragraph.</p> 
<button onclick="myFunction()">test</button>
<!-- w  w w  .  ja  va  2  s. co m-->
<script>
function myFunction() {
    document.querySelector(".example").style.backgroundColor = "red";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to get the first <p> element in the document.


<!DOCTYPE html>
<html>
<body>
<p>This is a p element.</p>
<p>This is also a p element.</p>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from  www  .  j av  a 2s  .  c o  m-->
    document.querySelector("p").style.backgroundColor = "red";
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to get the first <p> element in the document with class="example".


<!DOCTYPE html>
<html>
<body>
<h2 class="example">A heading</h2>
<p class="example">A paragraph</p> 
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from w  w w .  ja  v a2s  . c om-->
    document.querySelector("p.example").style.backgroundColor = "red";
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 4

The following code shows how to change the text of an element with id="demo".


<!DOCTYPE html>
<html>
<body>
<p id="demo">This is a p element.</p>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from   w ww  . j  a v  a2s.  c  o  m-->
    document.querySelector("#demo").innerHTML = "Hello World!";
}
</script>

</body>
</html>

The code above is rendered as follows: