JavaScript document.querySelector()

The JavaScript querySelector() method is used to select the first element with the 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 the 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. You can learn about CSS if you want to go into detail.

JavaScript querySelector() syntax

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


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

JavaScript querySelector() example

Consider the following code as an example demonstrating the querySelector() function in JavaScript:

<!DOCTYPE html>
  <title>The querySelector() function in JavaScript</title>
  <h2>The querySelector() function</h2>
  <p id="message">This is an example of the querySelector() function.</p>
  <p>This is the second paragraph.</p>

    // Select the <p> element with the id "message"
    const message = document.querySelector("#message");

    // Change the text of the <p> element
    message.textContent = "The querySelector() function is awesome!";

The following snapshot shows the output produced by this JavaScript example demonstrating the "querySelector()" function:

javascript querySelector example

The querySelector() function is used to select the "P" element with the id "message" in this example. Once the element has been selected, we can use the textContent property to change the text inside the "P" element to "The querySelector() function is awesome!"

JavaScript Online Test

« Previous Tutorial Next Tutorial »

Liked this post? Share it!