Skip to content

JavaScript querySelector Method

  • by

The querySelector method in JavaScript is a powerful tool for selecting and retrieving elements from the Document Object Model (DOM) based on CSS-like selectors.

In JavaScript, the querySelector method is used to select and retrieve the first element that matches a specified CSS selector within the document.

The basic syntax for querySelector is as follows:

const element = document.querySelector(selector);

It allows developers to find the first element that matches a specified selector, such as an ID, a class, or an element type.

With querySelector, you can easily manipulate the selected element’s properties, attach event listeners, or perform various operations.

For example, if you want to select an element with the ID “myElement“, you can use the following code:

const element = document.querySelector("#myElement");

If you want to select an element with a specific class name, you can use a dot (.) followed by the class name in the selector:

const element = document.querySelector(".myClass");

You can also combine different selectors. For instance, if you want to select an element with the class “myClass” that is inside an element with the ID “myContainer“, you can use:

const element = document.querySelector("#myContainer .myClass");

Once you have selected an element, you can manipulate it, access its properties, or attach event listeners to it using the element variable.

JavaScript querySelector Method example

Simple example code that demonstrates the usage of the querySelector method in JavaScript:

<!DOCTYPE html>
<html>
<head>
  <title>querySelector Example</title>
  <style>
    .myClass {
      color: red;
    }
  </style>
</head>
<body>
  <div id="myContainer">
    <p class="myClass">Hello, World!</p>
    <p>This is a paragraph.</p>
    <p class="myClass">This is another paragraph.</p>
  </div>

  <script>
    // Select the first element with the class "myClass"
    const element = document.querySelector(".myClass");
    
    // Manipulate the element by changing its text content
    element.textContent = "Element selected using querySelector";
    
    // Add a CSS class to the element
    element.classList.add("highlight");

    // Attach a click event listener to the element
    element.addEventListener("click", function() {
      alert("You clicked the element!");
    });
  </script>
</body>
</html>

Output:

JavaScript querySelector Method

When you run this HTML file in a web browser, you’ll see the element with the class “myClass” being selected, modified, and interacted with using JavaScript.

Do comment if you have any doubts or suggestions on this JS DOM method topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading