i2tutorials

Javascript DOM- Query Selector

Javascript DOM- Query Selector

 

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

The querySelector() method only provides the first element that matches the specified selectors. To return all the matches CSS, use the querySelectorAll() method instead.

If the selector matches an ID in the document that is used several times, it returns the first matching element.

 

Note: An “id” should be unique within a page and should not be used more than once.

 

Syntax:

 

document.querySelector(CSS selectors)

 

Example:

 

<!DOCTYPE html>
<html>
<body>

<p>This is a p element.</p>

<p>This is also a p element.</p>

<p>Click the button to add a background color to the first p element in the document.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
 document.querySelector("p").style.backgroundColor = "red";
}
</script>

</body>
</html>

 

OUTPUT:

 

Javascript DOM- Query Selector

 

 

Exit mobile version