JavaScript querySelector() Method

You are Here:

JavaScript querySelector() Method

The querySelector() method returns the first element that matches a specified CSS selector(s) in the document. If no matches are found, null is returned.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>P 1</p> <p>P 2</p> <p>P 3</p> <script> var x = document.querySelector("p"); x.innerHTML = "Hello there!"; </script> </body> </html>

Syntax

document.querySelector(selectors)

Parameter Values

ValueTypeExplanation
selectorsRequiredSpecifies one or more CSS selectors to match the element.
Note: The selector must be a valid CSS syntax, or a SyntaxError exception will occur.

More Examples

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p class="point">P 1</p> <p class="point">P 2</p> <p class="point">P 3</p> <script> var x = document.querySelector(".point"); x.innerHTML = "Hello there!"; </script> </body> </html>

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p class="point">P 1</p> <p class="point1">P 2</p> <p class="point2">P 3</p> <script> var x = document.querySelector("p.point1"); x.innerHTML = "Hello there!"; </script> </body> </html>

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <div class="div1"> <h2>Heading</h2> <p>Paragraph</p> </div> <div class="div1"> <h2>Heading</h2> <p>Paragraph</p> </div> <script> var x = document.querySelector(".div1 > p"); x.style.color = "green"; </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author