JavaScript document.querySelector()

The JavaScript querySelector() method is used to select the first element with specified CSS selector. For example:

HTML with JavaScript Code
<!DOCTYPE html>

   <p>This is para one</p>
   <p class="redPara">This is para two</p>
   <p>This is para three</p>
   <p>This is para four</p>
   <p class="redPara">This is para five</p>
      document.querySelector(".redPara").style.color = "red";

This is para one

This is para two

This is para three

This is para four

This is para five

See, the first element with specified class name, that is redPara, was returned. And I've changed the style of that element.

Note - There are multiple ways to select an element, using CSS selectors. The details are described in its separate tutorial.

JavaScript querySelector() Syntax

The syntax of querySelector() method in JavaScript, is:


The x refers to a CSS selector. If no match found, null is returned.

JavaScript Online Test

« Previous Tutorial Next Tutorial »

Liked this article? Share it!

Like/follow us on social media for updates!