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

Bộ sưu tập scripts trong HTML DOM

Bộ sưu tập scripts trong HTML DOM trả về tập hợp của tất cả các phần tử <script> trong một tài liệu HTML.

Cú pháp

document.scripts

Thuộc tính của bộ sưu tập scripts

Thuộc tínhMô tả
lengthTrả về số lượng phần tử <script> trong bộ sưu tập.

Phương thức của bộ sưu tập scripts

Phương thứcMô tả
[index]Trả về phần tử <script> tại chỉ số được chỉ định.
item(index)Trả về phần tử <script> tại chỉ số được chỉ định.
namedItem(id)Trả về phần tử <script> với id được chỉ định.

Ví dụ

Ví dụ sử dụng bộ sưu tập scripts:

<!DOCTYPE html>
<html>
<head>
<style>
  html { height: 100%; }
  body {
    text-align: center;
    color: #fff;
    background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
    height: 100%;
  }
  p { font-weight: 700; font-size: 1.2rem; }
  ul { list-style-type: none; padding: 0; }
  .btn {
    background: #0197F6;
    border: none;
    height: 2rem;
    border-radius: 2px;
    width: 50%;
    margin: 2rem auto;
    display: block;
    color: #fff;
    outline: none;
    cursor: pointer;
  }
  .show { font-size: 1.5rem; font-weight: bold; }
</style>
</head>
<body>
<script> console.log("script one"); </script>
<h1>Demo bộ sưu tập scripts DOM</h1>
<p>Chào bạn, trang này có hai phần tử script:</p>
<script> console.log("script two"); </script>
<button onclick="show()" class="btn">Hiển thị số lượng Script</button>
<div class='show'></div>
<script>
  function show() {
    var scriptList = document.scripts;
    document.querySelector(".show").innerHTML = scriptList.length;
  }
</script>
</body>
</html>

Kết quả

Nhấn nút Hiển thị số lượng Script để hiển thị số lượng phần tử script.