HTML DOM querySelector() Method (original) (raw)
Last Updated : 29 Nov, 2024
The querySelector() method returns the first element that matches the specified Selector. It only gives one element from the HTML DOM if found else it returns null. To get all the matching elements, you can use the querySelectorAll() method.
**Syntax
// To search in complete documemt
ducument.querySelector(selectors);
// To search inside a specific element
element.querySelector("html-tag .class-name #element-id...");
**selectors: It is a string containing the CSS Selectors.
**Return value: The first element that matches the selectors if found else null.
HTML `
This is paragraph 1.
This is paragraph 2.
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
// Select the first p element
let e = document.querySelector("p");
// Dynamically apply styling
// to the first p element
e.style.backgroundColor = "Green";
e.style.color = "white";
}
</script>
`
**Output:
HTML DOM querySelector Method Example