Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Phương thức deleteCaption() của Table trong HTML DOM

Phương thức deleteCaption() của đối tượng HTMLTableElement xóa phần tử <caption> đầu tiên (và duy nhất) khỏi bảng. Nếu bảng không có caption, phương thức không làm gì.

Cú pháp

tableElement.deleteCaption()

Ví dụ: Xóa caption bảng

<!DOCTYPE html>
<html>
<style>
  body { color: #000; background: lightblue; height: 100vh; text-align: center; }
  table { margin: 2rem auto; border-collapse: collapse; }
  caption { color: #db133a; font-weight: bold; margin-bottom: 0.5rem; }
  .btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }

<body>
  <h1>Demo: table.deleteCaption()</h1>
  <table border="2" id="demoTable">
    <caption>Danh sách sinh viên</caption>
    <tr><th>Tên</th><th>Mã SV</th></tr>
    <tr><td>An</td><td>071717</td></tr>
    <tr><td>Bình</td><td>031717</td></tr>
  </table>
  <button onclick="removeCaption()" class="btn">Xóa Caption</button>
  <script>
    function removeCaption() {
      var table = document.getElementById('demoTable');
      table.deleteCaption();
    }
  </script>
</body>
</html>

Kết quả:

  1. Ban đầu: Tiêu đề "Danh sách sinh viên" hiển thị trên bảng.
  2. Sau khi nhấn "Xóa Caption": Tiêu đề biến mất.
  3. Phương thức đối ngược: createCaption()

    var cap = table.createCaption();
    cap.innerHTML = "Tiêu đề mới";

    Lưu ý

    • Bảng chỉ có tối đa 1 <caption>.
    • deleteCaption() an toàn để gọi lặp lại (idempotent).
    • Caption nên mô tả succinct (ngắn gọn) nội dung bảng cho accessibility (screen reader đọc caption trước).