JS querySelector

The querySelector() method in JavaScript is a powerful tool for selecting elements from the DOM. It allows you to retrieve the first element that matches a specified CSS selector or group of selectors. This method simplifies element selection and manipulation, especially when dealing with complex or specific criteria.

Purpose: To find and return the first element that matches the specified CSS selector(s).

Return Value: The first matching element or null if no matches are found.

Scope: It is a method of the Document interface and can be used to search within the entire document.

Syntax:

element = document.querySelector(selectors);

• selectors: A string containing one or more CSS selectors separated by commas. This string defines the criteria for selecting the element(s).

How querySelector() Works

querySelector() uses a depth-first, pre-order traversal of the DOM. This means it starts searching from the top of the document and moves down through the hierarchy, checking each element in the order they appear. It returns the first element that matches the selector(s) and stops searching once a match is found.

Here are a few examples demonstrating how to use querySelector() to select elements from the DOM:

Example 1: Selecting a Single Element by ID

<div id="myDiv">Way To Code Technologies</div>
<script>
  var element = document.querySelector("#myDiv");
  console.log(element.textContent); // Output: Way To Code Technologies
</script>

Example 2: Selecting an Element by Class Name

<p class="myClass">This is a paragraph.</p>
<p class="myClass">Another paragraph.</p>
<script>
  var element = document.querySelector(".myClass");
  console.log(element.textContent); // Output: This is a paragraph.
</script>

Example 3: Selecting an Element by Attribute

<input type="text" name="username" placeholder="Enter your username">
<script>
  var element = document.querySelector("input[name='username']");
  console.log(element.placeholder); // Output: Enter your username
</script>

Output: