Điều gì xảy ra nếu nhiều phần tử HTML có cùng một ID?

Thuộc tính toàn cầu id xác định một mã định danh (ID) phải là duy nhất trong toàn bộ tài liệu. Mục đích của nó là xác định thành phần khi liên kết (dùng a ), viết mã lệnh hoặc tạo kiểu (bằng CSS)

Cảnh báo. Giá trị của thuộc tính này là một chuỗi mờ. điều này có nghĩa là các tác giả web không nên dựa vào nó để truyền tải thông tin mà con người có thể đọc được (mặc dù ID của bạn có thể đọc được ở một mức độ nào đó có thể hữu ích cho việc hiểu mã, e. g. xem xét ________ 87 _______ và ________ 88 _______)

Giá trị của id không được chứa khoảng trắng (dấu cách, tab, v.v. ). Các trình duyệt coi ID không phù hợp có chứa khoảng trắng như thể khoảng trắng là một phần của ID. Ngược lại với thuộc tính cho phép các giá trị được phân tách bằng dấu cách, các phần tử chỉ có thể có một giá trị ID duy nhất

Ghi chú. Về mặt kỹ thuật, giá trị cho thuộc tính id có thể chứa bất kỳ ký tự nào, ngoại trừ ký tự khoảng trắng. Tuy nhiên, để tránh các lỗi vô ý, chỉ nên sử dụng các chữ cái ASCII, chữ số, '_''-' và giá trị cho thuộc tính id phải bắt đầu bằng một chữ cái. Ví dụ, . có một ý nghĩa đặc biệt trong CSS (nó hoạt động như một bộ chọn lớp). Trừ khi bạn cẩn thận thoát nó trong CSS, nếu không nó sẽ không được công nhận là một phần giá trị của thuộc tính id. Rất dễ quên làm điều này, dẫn đến các lỗi trong mã của bạn khó phát hiện

Thuộc tính điều hướng DOM tuyệt vời khi các phần tử gần nhau. Nếu họ không thì sao?

Có các phương pháp tìm kiếm bổ sung cho điều đó

Nếu một phần tử có thuộc tính

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
3, chúng ta có thể lấy phần tử đó bằng cách sử dụng phương thức
<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
4, bất kể nó ở đâu

Ví dụ

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // get the element
  let elem = document.getElementById('elem');

  // make its background red
  elem.style.background = 'red';
</script>

Ngoài ra, có một biến toàn cục được đặt tên bởi

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
3 tham chiếu đến phần tử

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>

…Đó là trừ khi chúng ta khai báo một biến JavaScript có cùng tên, thì nó sẽ được ưu tiên

<div id="elem"></div>

<script>
  let elem = 5; // now elem is 5, not a reference to <div id="elem">

  alert(elem); // 5
</script>

Vui lòng không sử dụng các biến toàn cục có tên id để truy cập các phần tử

Hành vi này được mô tả, nhưng nó được hỗ trợ chủ yếu để tương thích

Trình duyệt cố gắng giúp chúng tôi bằng cách trộn các không gian tên của JS và DOM. Điều đó tốt cho các tập lệnh đơn giản, được đưa vào HTML, nhưng nhìn chung không phải là điều tốt. Có thể có xung đột đặt tên. Ngoài ra, khi một người đọc mã JS và không có HTML trong chế độ xem, thì không rõ biến đó đến từ đâu

Ở đây trong hướng dẫn này, chúng tôi sử dụng

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
3 để tham chiếu trực tiếp một phần tử cho ngắn gọn, khi rõ ràng phần tử đó đến từ đâu

Trong cuộc sống thực

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
7 là phương pháp ưa thích

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
3 phải là duy nhất

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
3 phải là duy nhất. Chỉ có thể có một phần tử trong tài liệu với
<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
3 đã cho

Nếu có nhiều phần tử có cùng

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
3, thì hành vi của các phương thức sử dụng nó là không thể đoán trước, e. g.
<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
7 có thể trả lại ngẫu nhiên bất kỳ phần tử nào như vậy. Vì vậy, vui lòng tuân theo quy tắc và giữ cho
<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
3 là duy nhất

Chỉ

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
7, không phải
<div id="elem"></div>

<script>
  let elem = 5; // now elem is 5, not a reference to <div id="elem">

  alert(elem); // 5
</script>
5

Phương thức

<div id="elem"></div>

<script>
  let elem = 5; // now elem is 5, not a reference to <div id="elem">

  alert(elem); // 5
</script>
6 chỉ có thể được gọi trên đối tượng
<div id="elem"></div>

<script>
  let elem = 5; // now elem is 5, not a reference to <div id="elem">

  alert(elem); // 5
</script>
7. Nó tìm kiếm
<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
3 đã cho trong toàn bộ tài liệu

Cho đến nay, phương pháp linh hoạt nhất,

<div id="elem"></div>

<script>
  let elem = 5; // now elem is 5, not a reference to <div id="elem">

  alert(elem); // 5
</script>
9 trả về tất cả các phần tử bên trong
<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
  }
</script>
0 khớp với bộ chọn CSS đã cho

Ở đây chúng tôi tìm kiếm tất cả các phần tử

<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
  }
</script>
1 là phần tử con cuối cùng

<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
  }
</script>

Phương pháp này thực sự mạnh mẽ, bởi vì bất kỳ bộ chọn CSS nào cũng có thể được sử dụng

Cũng có thể sử dụng các lớp giả

Các lớp giả trong bộ chọn CSS như

<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
  }
</script>
2 và
<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
  }
</script>
3 cũng được hỗ trợ. Chẳng hạn,
<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
  }
</script>
4 sẽ trả về tập hợp có các phần tử mà con trỏ hiện đã kết thúc (theo thứ tự lồng nhau. từ lớp ngoài cùng
<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
  }
</script>
5 đến lớp lồng nhau nhất)

Lệnh gọi tới

<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
  }
</script>
6 trả về phần tử đầu tiên cho bộ chọn CSS đã cho

Nói cách khác, kết quả giống như

<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
  }
</script>
7, nhưng cái sau đang tìm kiếm tất cả các phần tử và chọn một phần tử, trong khi
<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
  }
</script>
8 chỉ tìm kiếm một phần tử. Vì vậy, nó nhanh hơn và cũng ngắn hơn để viết

Các phương pháp trước đó là tìm kiếm DOM

Nó không tìm kiếm bất cứ thứ gì, nó chỉ kiểm tra xem

<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
  }
</script>
0 có khớp với bộ chọn CSS đã cho hay không. Nó trả về
<a href="http://example.com/file.zip">...</a>
<a href="http://ya.ru">...</a>

<script>
  // can be any collection instead of document.body.children
  for (let elem of document.body.children) {
    if (elem.matches('a[href$="zip"]')) {
      alert("The archive reference: " + elem.href );
    }
  }
</script>
0 hoặc
<a href="http://example.com/file.zip">...</a>
<a href="http://ya.ru">...</a>

<script>
  // can be any collection instead of document.body.children
  for (let elem of document.body.children) {
    if (elem.matches('a[href$="zip"]')) {
      alert("The archive reference: " + elem.href );
    }
  }
</script>
1

Phương thức này rất hữu ích khi chúng ta đang lặp lại các phần tử (như trong một mảng hoặc thứ gì đó) và cố gắng lọc ra những phần tử mà chúng ta quan tâm

Ví dụ

<a href="http://example.com/file.zip">...</a>
<a href="http://ya.ru">...</a>

<script>
  // can be any collection instead of document.body.children
  for (let elem of document.body.children) {
    if (elem.matches('a[href$="zip"]')) {
      alert("The archive reference: " + elem.href );
    }
  }
</script>

Tổ tiên của một phần tử là. cha mẹ, cha mẹ của cha mẹ, cha mẹ của nó, v.v. Tổ tiên cùng nhau tạo thành chuỗi cha mẹ từ phần tử đến đỉnh

Phương thức

<a href="http://example.com/file.zip">...</a>
<a href="http://ya.ru">...</a>

<script>
  // can be any collection instead of document.body.children
  for (let elem of document.body.children) {
    if (elem.matches('a[href$="zip"]')) {
      alert("The archive reference: " + elem.href );
    }
  }
</script>
2 tìm tổ tiên gần nhất khớp với bộ chọn CSS. Bản thân
<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
  }
</script>
0 cũng được đưa vào tìm kiếm

Nói cách khác, phương thức

<a href="http://example.com/file.zip">...</a>
<a href="http://ya.ru">...</a>

<script>
  // can be any collection instead of document.body.children
  for (let elem of document.body.children) {
    if (elem.matches('a[href$="zip"]')) {
      alert("The archive reference: " + elem.href );
    }
  }
</script>
4 đi lên từ phần tử và kiểm tra từng phần tử cha. Nếu nó khớp với bộ chọn, thì quá trình tìm kiếm sẽ dừng lại và tổ tiên được trả về

Ví dụ

<h1>Contents</h1>

<div class="contents">
  <ul class="book">
    <li class="chapter">Chapter 1</li>
    <li class="chapter">Chapter 2</li>
  </ul>
</div>

<script>
  let chapter = document.querySelector('.chapter'); // LI

  alert(chapter.closest('.book')); // UL
  alert(chapter.closest('.contents')); // DIV

  alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
</script>

Ngoài ra còn có các phương pháp khác để tìm kiếm các nút theo thẻ, lớp, v.v.

Ngày nay, chúng chủ yếu là lịch sử, vì

<a href="http://example.com/file.zip">...</a>
<a href="http://ya.ru">...</a>

<script>
  // can be any collection instead of document.body.children
  for (let elem of document.body.children) {
    if (elem.matches('a[href$="zip"]')) {
      alert("The archive reference: " + elem.href );
    }
  }
</script>
5 mạnh mẽ hơn và viết ngắn hơn

Vì vậy, ở đây chúng tôi trình bày chúng chủ yếu để hoàn thiện, trong khi bạn vẫn có thể tìm thấy chúng trong các tập lệnh cũ

  • <a href="http://example.com/file.zip">...</a>
    <a href="http://ya.ru">...</a>
    
    <script>
      // can be any collection instead of document.body.children
      for (let elem of document.body.children) {
        if (elem.matches('a[href$="zip"]')) {
          alert("The archive reference: " + elem.href );
        }
      }
    </script>
    6 tìm kiếm các phần tử với thẻ đã cho và trả về bộ sưu tập của chúng. Tham số
    <a href="http://example.com/file.zip">...</a>
    <a href="http://ya.ru">...</a>
    
    <script>
      // can be any collection instead of document.body.children
      for (let elem of document.body.children) {
        if (elem.matches('a[href$="zip"]')) {
          alert("The archive reference: " + elem.href );
        }
      }
    </script>
    7 cũng có thể là dấu sao
    <a href="http://example.com/file.zip">...</a>
    <a href="http://ya.ru">...</a>
    
    <script>
      // can be any collection instead of document.body.children
      for (let elem of document.body.children) {
        if (elem.matches('a[href$="zip"]')) {
          alert("The archive reference: " + elem.href );
        }
      }
    </script>
    8 cho “bất kỳ thẻ nào”
  • <a href="http://example.com/file.zip">...</a>
    <a href="http://ya.ru">...</a>
    
    <script>
      // can be any collection instead of document.body.children
      for (let elem of document.body.children) {
        if (elem.matches('a[href$="zip"]')) {
          alert("The archive reference: " + elem.href );
        }
      }
    </script>
    9 trả về các phần tử có lớp CSS đã cho
  • <h1>Contents</h1>
    
    <div class="contents">
      <ul class="book">
        <li class="chapter">Chapter 1</li>
        <li class="chapter">Chapter 2</li>
      </ul>
    </div>
    
    <script>
      let chapter = document.querySelector('.chapter'); // LI
    
      alert(chapter.closest('.book')); // UL
      alert(chapter.closest('.contents')); // DIV
    
      alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
    </script>
    0 trả về các phần tử có thuộc tính
    <h1>Contents</h1>
    
    <div class="contents">
      <ul class="book">
        <li class="chapter">Chapter 1</li>
        <li class="chapter">Chapter 2</li>
      </ul>
    </div>
    
    <script>
      let chapter = document.querySelector('.chapter'); // LI
    
      alert(chapter.closest('.book')); // UL
      alert(chapter.closest('.contents')); // DIV
    
      alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
    </script>
    1 đã cho, trên toàn bộ tài liệu. Rất hiếm khi được sử dụng

Ví dụ

// get all divs in the document
let divs = document.getElementsByTagName('div');

Hãy tìm tất cả các thẻ

<h1>Contents</h1>

<div class="contents">
  <ul class="book">
    <li class="chapter">Chapter 1</li>
    <li class="chapter">Chapter 2</li>
  </ul>
</div>

<script>
  let chapter = document.querySelector('.chapter'); // LI

  alert(chapter.closest('.book')); // UL
  alert(chapter.closest('.contents')); // DIV

  alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
</script>
2 bên trong bảng

<table id="table">
  <tr>
    <td>Your age:</td>

    <td>
      <label>
        <input type="radio" name="age" value="young" checked> less than 18
      </label>
      <label>
        <input type="radio" name="age" value="mature"> from 18 to 50
      </label>
      <label>
        <input type="radio" name="age" value="senior"> more than 60
      </label>
    </td>
  </tr>
</table>

<script>
  let inputs = table.getElementsByTagName('input');

  for (let input of inputs) {
    alert( input.value + ': ' + input.checked );
  }
</script>

Đừng quên lá thư

<h1>Contents</h1>

<div class="contents">
  <ul class="book">
    <li class="chapter">Chapter 1</li>
    <li class="chapter">Chapter 2</li>
  </ul>
</div>

<script>
  let chapter = document.querySelector('.chapter'); // LI

  alert(chapter.closest('.book')); // UL
  alert(chapter.closest('.contents')); // DIV

  alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
</script>
3

Các nhà phát triển mới làm quen đôi khi quên chữ cái

<h1>Contents</h1>

<div class="contents">
  <ul class="book">
    <li class="chapter">Chapter 1</li>
    <li class="chapter">Chapter 2</li>
  </ul>
</div>

<script>
  let chapter = document.querySelector('.chapter'); // LI

  alert(chapter.closest('.book')); // UL
  alert(chapter.closest('.contents')); // DIV

  alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
</script>
3. Nghĩa là, họ cố gắng gọi
<h1>Contents</h1>

<div class="contents">
  <ul class="book">
    <li class="chapter">Chapter 1</li>
    <li class="chapter">Chapter 2</li>
  </ul>
</div>

<script>
  let chapter = document.querySelector('.chapter'); // LI

  alert(chapter.closest('.book')); // UL
  alert(chapter.closest('.contents')); // DIV

  alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
</script>
5 thay vì
<h1>Contents</h1>

<div class="contents">
  <ul class="book">
    <li class="chapter">Chapter 1</li>
    <li class="chapter">Chapter 2</li>
  </ul>
</div>

<script>
  let chapter = document.querySelector('.chapter'); // LI

  alert(chapter.closest('.book')); // UL
  alert(chapter.closest('.contents')); // DIV

  alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
</script>
6

Chữ cái

<h1>Contents</h1>

<div class="contents">
  <ul class="book">
    <li class="chapter">Chapter 1</li>
    <li class="chapter">Chapter 2</li>
  </ul>
</div>

<script>
  let chapter = document.querySelector('.chapter'); // LI

  alert(chapter.closest('.book')); // UL
  alert(chapter.closest('.contents')); // DIV

  alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
</script>
3 không có trong
<div id="elem"></div>

<script>
  let elem = 5; // now elem is 5, not a reference to <div id="elem">

  alert(elem); // 5
</script>
6, bởi vì nó trả về một phần tử duy nhất. Nhưng
<h1>Contents</h1>

<div class="contents">
  <ul class="book">
    <li class="chapter">Chapter 1</li>
    <li class="chapter">Chapter 2</li>
  </ul>
</div>

<script>
  let chapter = document.querySelector('.chapter'); // LI

  alert(chapter.closest('.book')); // UL
  alert(chapter.closest('.contents')); // DIV

  alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
</script>
9 trả về một tập hợp các phần tử, vì vậy có
<h1>Contents</h1>

<div class="contents">
  <ul class="book">
    <li class="chapter">Chapter 1</li>
    <li class="chapter">Chapter 2</li>
  </ul>
</div>

<script>
  let chapter = document.querySelector('.chapter'); // LI

  alert(chapter.closest('.book')); // UL
  alert(chapter.closest('.contents')); // DIV

  alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
</script>
3 bên trong

Nó trả về một bộ sưu tập, không phải một phần tử

Một sai lầm phổ biến khác của người mới là viết

// doesn't work
document.getElementsByTagName('input').value = 5;

Điều đó sẽ không hiệu quả, bởi vì nó lấy một tập hợp các đầu vào và gán giá trị cho nó thay vì cho các phần tử bên trong nó

Chúng ta nên lặp lại bộ sưu tập hoặc lấy một phần tử theo chỉ mục của nó, sau đó gán, như thế này

// should work (if there's an input)
document.getElementsByTagName('input')[0].value = 5;

Tìm kiếm _______45_______1 phần tử

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
0

Tất cả các phương pháp

// get all divs in the document
let divs = document.getElementsByTagName('div');
2 trả về một bộ sưu tập trực tiếp. Các bộ sưu tập như vậy luôn phản ánh trạng thái hiện tại của tài liệu và “tự động cập nhật” khi nó thay đổi

Trong ví dụ bên dưới, có hai tập lệnh

  1. Cái đầu tiên tạo một tham chiếu đến bộ sưu tập của
    // get all divs in the document
    let divs = document.getElementsByTagName('div');
    3. Hiện tại, chiều dài của nó là
    // get all divs in the document
    let divs = document.getElementsByTagName('div');
    4
  2. Các tập lệnh thứ hai chạy sau khi trình duyệt gặp một
    // get all divs in the document
    let divs = document.getElementsByTagName('div');
    3 nữa, vì vậy độ dài của nó là
    // get all divs in the document
    let divs = document.getElementsByTagName('div');
    6

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
1

Ngược lại,

// get all divs in the document
let divs = document.getElementsByTagName('div');
7 trả về một bộ sưu tập tĩnh. Nó giống như một mảng các phần tử cố định

Nếu chúng ta sử dụng nó thay thế, thì cả hai tập lệnh đều xuất ra

// get all divs in the document
let divs = document.getElementsByTagName('div');
4

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
2

Bây giờ chúng ta có thể dễ dàng nhận thấy sự khác biệt. Bộ sưu tập tĩnh không tăng sau khi xuất hiện một

// get all divs in the document
let divs = document.getElementsByTagName('div');
9 mới trong tài liệu

Có 6 phương pháp chính để tìm kiếm các nút trong DOM

Phương thứcTìm kiếm theo. Có thể gọi một phần tử không?Live?
<a href="http://example.com/file.zip">...</a>
<a href="http://ya.ru">...</a>

<script>
  // can be any collection instead of document.body.children
  for (let elem of document.body.children) {
    if (elem.matches('a[href$="zip"]')) {
      alert("The archive reference: " + elem.href );
    }
  }
</script>
5CSS-selector✔-
// get all divs in the document
let divs = document.getElementsByTagName('div');
7CSS-selector✔-
<div id="elem"></div>

<script>
  let elem = 5; // now elem is 5, not a reference to <div id="elem">

  alert(elem); // 5
</script>
6
<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // elem is a reference to DOM-element with id="elem"
  elem.style.background = 'red';

  // id="elem-content" has a hyphen inside, so it can't be a variable name
  // ...but we can access it using square brackets: window['elem-content']
</script>
3--
<table id="table">
  <tr>
    <td>Your age:</td>

    <td>
      <label>
        <input type="radio" name="age" value="young" checked> less than 18
      </label>
      <label>
        <input type="radio" name="age" value="mature"> from 18 to 50
      </label>
      <label>
        <input type="radio" name="age" value="senior"> more than 60
      </label>
    </td>
  </tr>
</table>

<script>
  let inputs = table.getElementsByTagName('input');

  for (let input of inputs) {
    alert( input.value + ': ' + input.checked );
  }
</script>
4
<h1>Contents</h1>

<div class="contents">
  <ul class="book">
    <li class="chapter">Chapter 1</li>
    <li class="chapter">Chapter 2</li>
  </ul>
</div>

<script>
  let chapter = document.querySelector('.chapter'); // LI

  alert(chapter.closest('.book')); // UL
  alert(chapter.closest('.contents')); // DIV

  alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
</script>
1-✔
<h1>Contents</h1>

<div class="contents">
  <ul class="book">
    <li class="chapter">Chapter 1</li>
    <li class="chapter">Chapter 2</li>
  </ul>
</div>

<script>
  let chapter = document.querySelector('.chapter'); // LI

  alert(chapter.closest('.book')); // UL
  alert(chapter.closest('.contents')); // DIV

  alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
</script>
9tag hoặc
<table id="table">
  <tr>
    <td>Your age:</td>

    <td>
      <label>
        <input type="radio" name="age" value="young" checked> less than 18
      </label>
      <label>
        <input type="radio" name="age" value="mature"> from 18 to 50
      </label>
      <label>
        <input type="radio" name="age" value="senior"> more than 60
      </label>
    </td>
  </tr>
</table>

<script>
  let inputs = table.getElementsByTagName('input');

  for (let input of inputs) {
    alert( input.value + ': ' + input.checked );
  }
</script>
7✔✔
<table id="table">
  <tr>
    <td>Your age:</td>

    <td>
      <label>
        <input type="radio" name="age" value="young" checked> less than 18
      </label>
      <label>
        <input type="radio" name="age" value="mature"> from 18 to 50
      </label>
      <label>
        <input type="radio" name="age" value="senior"> more than 60
      </label>
    </td>
  </tr>
</table>

<script>
  let inputs = table.getElementsByTagName('input');

  for (let input of inputs) {
    alert( input.value + ': ' + input.checked );
  }
</script>
8class✔✔

Cho đến nay, những thứ được sử dụng nhiều nhất là

<a href="http://example.com/file.zip">...</a>
<a href="http://ya.ru">...</a>

<script>
  // can be any collection instead of document.body.children
  for (let elem of document.body.children) {
    if (elem.matches('a[href$="zip"]')) {
      alert("The archive reference: " + elem.href );
    }
  }
</script>
5 và
// get all divs in the document
let divs = document.getElementsByTagName('div');
7, nhưng
// doesn't work
document.getElementsByTagName('input').value = 5;
1 có thể hữu ích một cách rời rạc hoặc được tìm thấy trong các chữ viết cũ

bên cạnh đó

  • // doesn't work
    document.getElementsByTagName('input').value = 5;
    2 để kiểm tra xem
    <ul>
      <li>The</li>
      <li>test</li>
    </ul>
    <ul>
      <li>has</li>
      <li>passed</li>
    </ul>
    <script>
      let elements = document.querySelectorAll('ul > li:last-child');
    
      for (let elem of elements) {
        alert(elem.innerHTML); // "test", "passed"
      }
    </script>
    0 có khớp với bộ chọn CSS đã cho hay không
  • <a href="http://example.com/file.zip">...</a>
    <a href="http://ya.ru">...</a>
    
    <script>
      // can be any collection instead of document.body.children
      for (let elem of document.body.children) {
        if (elem.matches('a[href$="zip"]')) {
          alert("The archive reference: " + elem.href );
        }
      }
    </script>
    2 để tìm tổ tiên gần nhất khớp với bộ chọn CSS đã cho. Bản thân
    <ul>
      <li>The</li>
      <li>test</li>
    </ul>
    <ul>
      <li>has</li>
      <li>passed</li>
    </ul>
    <script>
      let elements = document.querySelectorAll('ul > li:last-child');
    
      for (let elem of elements) {
        alert(elem.innerHTML); // "test", "passed"
      }
    </script>
    0 cũng được kiểm tra

Và hãy đề cập đến một phương pháp khác ở đây để kiểm tra mối quan hệ cha-con, vì nó đôi khi hữu ích

Bạn có thể có nhiều phần tử HTML với cùng một ID không?

Thuộc tính id HTML được sử dụng để chỉ định một id duy nhất cho một phần tử HTML. Bạn không thể có nhiều phần tử có cùng id trong tài liệu HTML .

ID trùng lặp có được phép trong HTML không?

ID trùng lặp là lỗi xác thực phổ biến có thể làm hỏng khả năng truy cập nhãn , e. g. , trường biểu mẫu, ô tiêu đề bảng. Để khắc phục sự cố, hãy thay đổi giá trị ID nếu được sử dụng nhiều lần để đảm bảo mỗi giá trị là duy nhất.