written 8.3 years ago by | • modified 2.9 years ago |
Subject: Advanced Internet Technology
Topic: Responsive web design with HTML5 and CSS3
Difficulty: High
written 8.3 years ago by | • modified 2.9 years ago |
Subject: Advanced Internet Technology
Topic: Responsive web design with HTML5 and CSS3
Difficulty: High
written 8.3 years ago by | • modified 8.3 years ago |
The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.
Note: The querySelector() method only returns the first element that matches the specified selectors. To return all the matches, use the querySelectorAll() method instead. If the selector matches an ID in document that is used several times (Note that an "id" should be unique within a page and should not used more than once), it returns the first matching element.
Syntax
document.querySelector(CSS selectors)
Parameter Values
Parameter | Type | Description |
---|---|---|
CSS selectors | String | Required. Specifies one or more CSS selectors to match the element. These are used to select HTML elements based on their id, classes, types, attributes, values of attributes, etc. For multiple selectors, separate each selector with a comma. The returned element depends on which element that is first found in the document (See "More Examples"). |
Example:
<!DOCTYPE html>
<html>
<body>
<h2 class="example">A heading with class="example"</h2>
<p class="example">A paragraph with class="example".</p>
<p>Click the button to add a background color to the first p element in the document with class="example".</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.querySelector("p.example").style.backgroundColor = "red";
}
</script>
</body>
</html>
Output: