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

Thuộc tính length của Select trong HTML DOM

Thuộc tính length của HTML DOM Select trả về số lượng phần tử <option> bên trong một danh sách thả xuống (drop-down list) trong tài liệu HTML.

Cú pháp

Cú pháp như sau:

object.length

Ví dụ

Dưới đây là ví dụ về thuộc tính length của HTML DOM Select:

<!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;    }    .drop-down{       width:35%;       border:2px solid #fff;       font-weight:bold;       padding:8px;    }    .btn{       background:#0197F6;       border:none;       height:2rem;       border-radius:2px;       width:35%;       margin:2rem auto;       display:block;       color:#fff;       outline:none;       cursor:pointer;    }    .show{       font-size:1.5rem;       font-weight:bold;    } </style> </head> <body> <h1>Demo thuộc tính length của DOM Select</h1> <p>Chào bạn, hãy chọn môn học yêu thích:</p> <select class='drop-down'> <option>Vật lý</option> <option>Toán học</option> <option>Hóa học</option> <option>Tiếng Anh</option> </select> <button onclick="showLength()" class="btn">Nhấn để lấy số lượng tùy chọn</button> <div class="show"></div> <script>    function showLength() {       var dropDown = document.querySelector(".drop-down");       var showMsg = document.querySelector(".show");       showMsg.innerHTML ="Số lượng tùy chọn: " + dropDown.length;    } </script> </body> </html>

Kết quả

Đoạn mã trên sẽ cho kết quả như sau:

Thuộc tính length của Select trong HTML DOM

Nhấn vào nút 「Nhấn để lấy số lượng tùy chọn」 để lấy số lượng tùy chọn có trong danh sách thả xuống.

Thuộc tính length của Select trong HTML DOM