HTML - DOM querySelectorAll() Method



The HTML DOM querySelectorAll() method allows you to select and access all HTML element that matches a given CSS selector(s) within the document.

The CSS selectors are used to find or select elements in a document that you want to style or manipulate. For example, you can use IDs, class names, and various other selectors to target specific elements.

Syntax

Following is the syntax of the HTML DOM querySelectorAll() function −

element.querySelectorAll(CSS_selectors);

Parameters

This method accepts a single parameter as mentioned below −

Parameter Description
CSS_selectors A string that defines the type of elements you want to select. It can be Id, classes, type of elements(such as <div>, or <p>), or even specific attributes and their values. To define multiple selectors, separate them with commas(,).

Return Value

This method returns a NodeList object that holds a collection of elements that matches the given CSS selector(s). If no matching element is found, it returns an empty 'NodeList'.

Example 1: Applying Styles to All Paragraphs

The following is the basic example of the HTML DOM querySelectorAll() method. It applies the styles to all paragraphs (<p>) elements in the document −

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM querySelectorAll() Method</title>
<style>
   .highlight {
       background-color: lightblue;
   }
</style>
</head>
<body>
<p>Applying Style to All Paragraphs.</p>
<p>Click the below button to add style</p>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<button onclick="applyHighlight()">Apply Highlight</button>
<script>
   function applyHighlight() {
      const para=document.querySelectorAll('p');
      para.forEach(para => {
         para.classList.add('highlight');
      });
   }
</script>
</body>
</html>

Example 2: Counting and Displaying List Items

This example counts and displays the total number of list (<li>) items in an unordered list using querySelectorAll() method −

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM querySelectorAll() Method</title>
</head>
<body>
<p>Click the button to see the count of List Items..</p> 
<ul id="myL">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
</ul>
<button onclick="countItems()">Count Items</button>
<p id="totalItems"></p>
<script>
   function countItems() {
      const i=document.querySelectorAll('#myL li');
      document.getElementById('totalItems').textContent = `Total items: ${i.length}`;
   }
</script>
</body>
</html>

Example 3: Adding Event Listener to All Element

This example shows how to use the querySelectorAll() method to select an element and add an event listener to all elements dynamically −

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM querySelectorAll() Method</title>
</head>
<body>
<p>Adding Event Listener to all element<p>  
<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>
<button id="btn3">Button 3</button>
<div id="output"></div>
<script>
   const bn=document.querySelectorAll('button');
   const opd = document.getElementById('output');
   bn.forEach(button => {
      button.addEventListener('click', () => {
         const buttonId = button.id;
         const message = `Button ${buttonId} clicked`;
         // Display message in output
         const msgP=document.createElement('p');
         msgP.textContent = message;
         opd.appendChild(msgP);
      });
   });
</script>
</body>
</html>

Example 4: Selecting and Modifying the Selected Table Cells

This example shows how to select and modify table cells using the querySelectorAll() method. The code includes a button, and when the button is clicked, it adds a highlight class to all table cells −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM querySelectorAll() Method</title>
<style>
   .highlight {
       background-color: violet;
   }
</style>
</head>
<body>
<p>Click button to apply style.</p>
<table id="myT" border="1">
    <tr>
       <td>Name</td>
       <td>Age</td>
    </tr>
    <tr>
       <td>John</td>
       <td>30</td>
    </tr>
    <tr>
       <td>Jane</td>
       <td>25</td>
   </tr>
</table>
<button onclick="highlightCells()">Highlight Cells</button>
<script>
   function highlightCells() {
      const c=document.querySelectorAll('#myT td');
      c.forEach(c => {
         c.classList.add('highlight');
      });
   }
</script>
</body>
</html>

Example 5: Filtering and Styling Particular Elements

This example shows how querySelectorAll() method can be used to select particular elements and apply different styles based on their position −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM querySelectorAll() Method</title>
<style>
   .even {
       color: green;
   }
   .odd {
       color: blue;
   }
</style>
</head>
<body>
<p>Selects specific elements and applies style to each... </p>
<ul id="MyL">
   <li>1</li>
   <li>2</li>
   <li>3</li>
   <li>4</li>
   <li>5</li>
</ul>
<button onclick="styleNumbers()">Style Numbers</button>
<script>
   function styleNumbers() {
      const i=document.querySelectorAll('#MyL li');
      i.forEach((i, index) => {
         if ((index + 1) % 2 === 0) {
            i.classList.add('even');
         } else {
            i.classList.add('odd');
         }
      });
   }
</script>
</body>
</html>

Example 6: Checking the Status of All checkboxes

This example shows how to use the querySelectorAll() method to check the states of all checkboxes. The code includes a <p> elements that are appended to a <div> element to display each checkbox's state −

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM querySelectorAll() Method</title>
</head>
<body>
<p>Check the status of the following checkboxes</p>
<p>Click the below button</p>
<input type="checkbox" id="checkbox1">
<label for="checkbox1">Checkbox 1</label><br>
<input type="checkbox" id="checkbox2">
<label for="checkbox2">Checkbox 2</label><br>
<input type="checkbox" id="checkbox3">
<label for="checkbox3">Checkbox 3</label><br>
<button onclick="checkStates()">Check States</button>
<div id="checkboxStatus"></div>
<script>
   function checkStates() {
      const checkboxes = document.querySelectorAll
      ('input[type="checkbox"]');
      const checkboxStatusDiv=document.getElementById
      ('checkboxStatus');
      checkboxStatusDiv.innerHTML = '';  
      checkboxes.forEach(checkbox => {
         const checkboxState = checkbox.checked 
         ? 'checked' : 'not checked';
         const checkboxStatus = 
         document.createElement('p');
         checkboxStatus.textContent = 
         `${checkbox.id} is ${checkboxState}.`;
         checkboxStatusDiv.appendChild
         (checkboxStatus);
      });
   }
</script>
</body>
</html>

Example 7: Selecting and Styling "ul" Element

This example shows how to use the querySelectorAll() method to select and style multiple elements. the code targets a <ul>element and applies the highlight class to all its child <li> elements −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM querySelectorAll() Method</title>
<style>
   .highlight {
      background-color: violet;
   }
</style>
</head>
<body>
<p>Click button to highlight the <ul> elements... </p>
<ul id="myL">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
</ul>
<button onclick="applyHighlight()">Apply Highlight</button>
<script>
   function applyHighlight() {
      const i=document.querySelectorAll('#myL li');
      i.forEach(i => {
         i.classList.add('highlight');
      });
   }
</script>
</body>
</html>

Example 8: Updating the Text of All "li" Items

This example shows how to change the text content of all elements matching a CSS selector using querySelectorAll() Method −

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM querySelectorAll() Method</title>
</head>
<body> 
<p>Change the text of all elements by clicking the below button.. </p>
<ul id="mL">
   <li>Chota</li>
   <li>Mighty</li>
   <li>Little</li>
</ul>
<button onclick="changeText()">Change Text</button>
<div id="output"></div>
<script>
   function changeText() {
      const i=document.querySelectorAll('#mL li');
      const names = 
      ['Chota Bheem','Mighty Raju','Little Krishna'];
      const opd = document.getElementById('output');
      opd.innerHTML = ''; 
      i.forEach((item, index) => {
         item.textContent = names[index];
         
         // Display updated text in output
         const newip=document.createElement('p');
         newip.textContent = `Changed text to: ${names[index]}`;
         opd.appendChild(newip);
      });
   }
</script>
</body>
</html>

Supported Browsers

Method Chrome Edge Firefox Safari Opera
querySelectorAll() Yes Yes Yes Yes Yes
html_dom_element_reference.htm
Advertisements