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

Phương thức remove() của Select trong HTML DOM

Phương thức remove() của HTML DOM Select xóa một tùy chọn khỏi danh sách thả xuống trong tài liệu HTML.

Cú pháp

Cú pháp như sau:

object.remove(index)

Ở đây, index đại diện cho chỉ số của tùy chọn cần xóa khỏi danh sách thả xuống.

Ví dụ

Dưới đây là ví dụ về phương thức remove() của HTML DOM Select:

<!DOCTYPE html> <html> <head> <style>    html{       height:100%;    }    body{       text-align:center;       color:#fff;       background: radial-gradient( circle farthest-corner at 23.1% 64.6%, rgba(129,125,254,1) 0%, rgba(111,167,254,1) 90% ) no-repeat;       height:100%;    }    p{       font-weight:700;       font-size:1.1rem;    }    .drop-down{       display:block;       width:35%;       border:2px solid #fff;       font-weight:bold;       padding:2px;       margin:1rem auto;       outline:none;    }    .btn{       background:orange;       border:none;       height:2rem;       border-radius:2px;       width:35%;       margin:2rem auto;       display:block;       color:#fff;       font-weight:bold;       outline:none;       cursor:pointer;    }    .show{       font-size:1.5rem;       font-weight:bold;    } </style> </head> <body> <h1>Demo phương thức remove() 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' name="Drop Down List"> <option>Vật lý</option> <option>Sinh học</option> <option>Toán học</option> </select> <button type="button" onclick="addSubject()" class="btn">Xóa môn Vật lý</button> <div class="show"></div> <script>    function addSubject() {       var dropDown = document.querySelector(".drop-down");       document.querySelector(".show").innerHTML="Đã xóa môn Vật lý";       dropDown.remove(0);    } </script> </body> </html>

Kết quả

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

Phương thức remove() của Select trong HTML DOM

Nhấn vào 「Xóa môn Vật lý」 để xóa môn đầu tiên, hiện tại là 「Vật lý」 trong danh sách thả xuống:

Phương thức remove() của Select trong HTML DOM