The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.
querySelector |
Yes | 8.0 | Yes | Yes | Yes |
document.querySelector(CSS selectors)
Parameter | Type | Description |
---|---|---|
CSS selectors | String | Required. CSS selectors to match the element. |
DOM Version: | Selectors Level 1 Document Object |
---|---|
Return Value: | A NodeList object, representing the first element that matches the specified CSS selector(s). |
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:
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:
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:
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: