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>
<html>
<body>

   <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>
   
   <script>
      document.querySelector(".redPara").style.color = "red";
   </script>
   
</body>
</html>
Output

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:

document.querySelector(x)

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

JavaScript Online Test


« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook




Subscribe Us on YouTube