HTML - DOM querySelectorAll() 方法



HTML DOM 的querySelectorAll()方法允許您選擇和訪問文件中與給定 CSS 選擇器匹配的所有 HTML 元素。

CSS 選擇器用於查詢或選擇文件中您想要設定樣式或操作的元素。例如,您可以使用 ID、類名和各種其他選擇器來定位特定元素。

語法

以下是 HTML DOM querySelectorAll() 函式的語法:

element.querySelectorAll(CSS_selectors);

引數

此方法接受如下所述的一個引數:

引數 描述
CSS_selectors 定義您想要選擇的元素型別的字串。它可以是 ID、類、元素型別(例如 <div> 或 <p>),甚至是特定的屬性及其值。要定義多個選擇器,請用逗號 (,) 分隔它們。

返回值

此方法返回一個 NodeList 物件,其中包含與給定 CSS 選擇器匹配的元素集合。如果找不到匹配的元素,則返回一個空的“NodeList”。

示例 1:將樣式應用於所有段落

以下是 HTML DOM querySelectorAll() 方法的基本示例。它將樣式應用於文件中的所有段落 (<p>) 元素:

<!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>

示例 2:計數和顯示列表項

此示例使用 querySelectorAll() 方法計算並顯示無序列表中的列表項 (<li>) 的總數:

<!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>

示例 3:向所有元素新增事件監聽器

此示例演示如何使用 querySelectorAll() 方法選擇元素並動態地向所有元素新增事件監聽器:

<!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>

示例 4:選擇和修改選定的表格單元格

此示例演示如何使用 querySelectorAll() 方法選擇和修改表格單元格。程式碼包含一個按鈕,單擊該按鈕時,它會將突出顯示類新增到所有表格單元格:

<!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>

示例 5:篩選和設定特定元素的樣式

此示例演示如何使用 querySelectorAll() 方法選擇特定元素並根據其位置應用不同的樣式:

<!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>

示例 6:檢查所有複選框的狀態

此示例演示如何使用 querySelectorAll() 方法檢查所有複選框的狀態。程式碼包含附加到 <div> 元素的 <p> 元素,以顯示每個複選框的狀態:

<!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>

示例 7:選擇和設定“ul”元素的樣式

此示例演示如何使用 querySelectorAll() 方法選擇和設定多個元素的樣式。程式碼的目標是 <ul> 元素,並將突出顯示類應用於其所有子 <li> 元素:

<!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>

示例 8:更新所有“li”項的文字

此示例演示如何使用 querySelectorAll() 方法更改與 CSS 選擇器匹配的所有元素的文字內容:

<!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>

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
querySelectorAll()
html_dom_element_reference.htm
廣告