HTML - DOM querySelector() 方法



HTML DOM 的querySelector() 方法允許您選擇並訪問文件中與給定 CSS 選擇器匹配的第一個 HTML 元素。

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

語法

以下是 HTML DOM querySelector() 方法的語法:

element.querySelector(CSS_selectors);

引數

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

引數 描述
CSS_selectors 一個字串,定義您要選擇的元素型別。它可以是 ID、類、元素型別(如 <div> 或 <p>),甚至特定的屬性及其值。

返回值

此方法返回與給定 CSS 選擇器匹配的第一個 HTML 元素。如果未找到匹配的元素,則返回“null”。

示例 1:將 Highlight 類應用於選定元素

以下是 HTML DOM querySelector() 方法的基本示例。當單擊按鈕時,它會將“highlight”類新增到匹配的段落 (<p>) 元素:

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM querySelector() Method</title>
<style>
   .highlight {
      background-color: lightblue;
   }
   button{
      margin: 5px 0px;
      padding: 8px;
   }
</style>
</head> 
<body>
<p>Selects the first element that matches the given CSS selector</p>
<h4>This is a heading</h4>
<p>This is a paragraph.</p>
<p class="hi">This is another paragraph with class="hi".</p>
<div>This is a div element.</div>
<button onclick="applyHighlight()">Apply Highlight</button>
<script>
function applyHighlight() {
    // Selecting the element with class "hi"
    const hele = document.querySelector('.hi');
    // Applying bold font weight and highlight 
    hele.style.fontWeight = 'bold';         
    hele.classList.add('highlight');      
    // Creating a new paragraph to display the action
    const resp = document.createElement('p');
    resp.textContent = 'Applied bold font weight to element with ' + 'class "highlight".'+ '.highlight';
    document.body.appendChild(resp);
}
</script>
</body>
</html>

示例 2:選擇並顯示元素文字

此示例演示了querySelector() 方法的使用,方法是選擇文件中的第一個 <p> 元素;然後它將該段落的文字內容顯示為輸出:

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM querySelector() Method</title>   
<style>
   .highlight {
       background-color: yellow;
   }
   button{
       margin: 5px 0px;
	   padding: 8px;
   }
</style>
</head>
<body> 
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p class="highlight">This is another paragraph with class="highlight"</p>
<div>This is a div element.</div>
<button onclick="showOutput()">Show Output</button>
<script>
   function showOutput() {
      // Selecting the first <p> element
      const firstP = document.querySelector('p');
      // Creating a new paragraph to display the result
      const resultP=document.createElement('p');
      resultP.textContent = "Selected paragraph text: "+
      "It selects the first element that matches " + 
      "the specified CSS selector ";
      // Displaying the result in a clean way
      document.body.appendChild(resultP);
   }
</script>
</body>
</html>

示例 3:選擇和更改文字內容

在下面的示例中,querySelector() 方法選擇一個 <div> 元素,並在單擊按鈕時使用新的文字內容對其進行修改:

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM querySelector() Method</title>
<style>
   button{
      margin: 5px 0px;
      padding: 8px;
   }
</style>
</head>
<body>
<p>Selecting and Changing Text Content</p> 
<div id="con">Original text content.</div>
<button onclick="changeContent()">Change Content</button>
<script>
   function changeContent() {
      const cele = document.querySelector('#con');
      // Changing text content of selected element
      cele.textContent = 'Updated text content!';
      // Creating a  paragraph for displaying action
      const resp = document.createElement('p');
      resp.textContent = 
      'Changed text content of element with ID "con".';
      
      // Displaying the result in a clean way
      document.body.appendChild(resp);
   }
</script>
</body>
</html>

示例 4:在選定元素上新增事件監聽器

以下示例顯示瞭如何使用querySelector() 方法選擇一個元素並動態新增事件監聽器:

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM querySelector() Method</title>
<style>
   button{
      margin: 5px 0px;
      padding: 8px;
   }
</style>
</head>
<body>
<p>Adding Event Listener on selected element...</p>  
<button id="myButton">Click Me!</button>
<div id="output"></div>  
<script>
   document.addEventListener('DOMContentLoaded',
   function() {
      const b=document.querySelector('#myButton');
      const op = document.querySelector('#output');
      b.addEventListener('click', function() { 
         output.innerHTML = '';
         const msg = document.createElement('p');
         msg.textContent = 'Button clicked!';
         op.appendChild(msg);
      });
   });
</script>
</body>
</html>

示例 5:選擇和修改表單元素

此示例顯示了querySelector() 方法如何選擇表單元素並在輸出面板中顯示其值:

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM querySelector() Method</title>
<style>
   button{
      margin: 5px 0px;
      padding: 8px;
   }
</style>
</head>
<body>
<p>Selects the form elements and modifies their values...</p> 
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<br><br>
<button type="button"onclick="submitForm()">Submit Form</button>
</form>
<div id="output"></div> 
<script>
   function submitForm() {
      const form=document.querySelector('#myForm');
      const uin = form.querySelector('#username');
      const pin = form.querySelector('#password');
      // Displaying form data in the output panel
      const op = document.querySelector('#output');
      op.innerHTML = `<p>Username: 
      ${uin.value}</p><p>Password: 
      ${pin.value}</p>`;
   }
</script>
</body>
</html>

示例 6:選擇和修改選定的表格行

在以下示例中,使用 querySelector() 方法修改表格行。它將“highlight”類新增到由年齡最小的人選擇的行:

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM querySelector() Method</title>
<style>
   button{
      margin: 5px 0px;
      padding: 8px;
   }
   .highlight {
      background-color: yellow;
   }
</style>
</head>
<body>
<p>Selects and adds highlight class on selected table row..</p> 
<table id="myTable" border="1">
   <thead>
   <tr>
      <th>Name</th>
      <th>Age</th>
   </tr>
   </thead>
   <tbody>
   <tr>
     <td>John</td>
     <td>25</td>
   </tr>
   <tr>
      <td>Jane</td>
      <td>30</td>
   </tr>
   </tbody>
</table>
<button onclick="highlightYoungest()">Highlight Youngest</button>
<script>
   function highlightYoungest() {
      const t=document.querySelector('#myTable');
      const r = t.querySelectorAll('tbody tr');
      
      // Finding the youngest person
      let youngestAge = Infinity;
      let youngestRow = null;
      
      r.forEach(row => {
         const age = parseInt(row.querySelector
         ('td:nth-child(2)').textContent);
         if (age < youngestAge) {
            youngestAge = age;
            youngestRow = row;
         }
      }); 
      youngestRow.classList.add('highlight');
      //creates new paragraph to display the result
      const rp = document.createElement('p');
      rp.textContent="Highlighted the youngest " + "person (Age: ${youngestAge}) in the table.";
      // Displaying the  in a clean way
      document.body.appendChild(rp);         
   }
</script>
</body>
</html>

示例 7:控制 Div 元素的可見性

下面的示例使用 querySelector() 方法控制元素的可見性。當單擊按鈕時,<div> 元素變為可見:

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM querySelector() Method</title>
<style>
   .hidden {
       display: none;
   }
   button{
      margin: 5px 0px;
      padding: 8px;
  }
</style>
</head>
<body>
<p>Controls the visibility of a <div> element...</p>
<button onclick="toggleVisibility()">Control Visibility</button>
<div id="myDiv">
<p>Click the button to hide me!</p>
</div>
<script>
   function toggleVisibility() {
      const d=document.querySelector('#myDiv');
      d.classList.toggle('hidden');
   }
</script>
</body>
</html>

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
querySelector() 是 4.0 是 8.0 是 3.5 是 3.2 是 10.0
html_dom_element_reference.htm
廣告