Danh sách DOMToken HTML
Danh sách DOMToken
DOMTokenList
là một tập hợp các mã thông báo được phân tách bằng dấu cách.
DOMTokenList
có thể được truy cập theo chỉ mục (bắt đầu từ 0).
Thuộc tính độ dài trả về số lượng mã thông báo trong DOMTokenList.
Ghi chú
Thuộc tính classList của một phần tử HTML đại diện cho DOMTokenList.
Thuộc tính và phương thức DOMTokenList
Name | Description |
---|---|
add() | Adds one or more tokens to the list |
contains() | Returns true if the list contains a class |
entries() | Returns an Iterator with key/value pairs from the list |
forEach() | Executes a callback function for each token in the list |
item() | Returns the token at a specified index |
keys() | Returns an Iterator with the keys in the list |
length | Returns the number of tokens in the list |
remove() | Removes one or more tokens from the list |
replace() | Replaces a token in the list |
supports() | Returns true if a token is one of an attribute's supported tokens |
toggle() | Toggles between tokens in the list |
value | Returns the token list as a string |
values() | Returns an Iterator with the values in the list |
Ví dụ
Thêm lớp "myStyle" vào một phần tử:
element.classList.add("myStyle");
Hãy tự mình thử »Xóa lớp "myStyle" khỏi một phần tử:
element.classList.remove("myStyle");
Hãy tự mình thử »Bật và tắt "myStyle":
element.classList.toggle("myStyle");
Hãy tự mình thử »Thêm ví dụ dưới đây.
Không phải là một mảng
DOMTokenList không phải là một mảng!
DOMTokenList có thể trông giống như một mảng nhưng thực tế không phải vậy.
Bạn có thể lặp qua DOMTokenList và tham chiếu mã thông báo của nó bằng một chỉ mục.
Nhưng bạn không thể sử dụng các phương thức Array như push(), pop() hoặc join() trên DOMTokenList.
Thêm nhiều lớp vào phần tử an:
element.classList.add("myStyle", "anotherClass", "thirdClass");
Hãy tự mình thử »Xóa nhiều lớp khỏi một phần tử:
element.classList.remove("myStyle", "anotherClass", "thirdClass");
Hãy tự mình thử »Lấy tên lớp của phần tử "myDIV":
<div id="myDIV" class="myStyle anotherClass thirdClass">
<p>I am myDIV.</p>
</div>
const list = document.getElementById("myDIV").classList;
Hãy tự mình thử »Xóa "anotherClass" nếu một phần tử có lớp "myStyle".
if (element.classList.contains("mystyle")) {
element.classList.remove("anotherClass");
}
Hãy tự mình thử »Chuyển đổi giữa các lớp để tạo nút thả xuống:
document.getElementById("myBtn").onclick = function() {myFunction()};
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
Hãy tự mình thử »Tạo một thanh điều hướng cố định:
// Get the navbar
const navbar = document.getElementById("navbar");
// Get the offset position of the navbar
const sticky = navbar.offsetTop;
// Add the sticky class to the navbar when you reach its scroll position
// Remove it when you leave the scroll position
function myFunction() {
if (window.pageYOffset
>= sticky) {
navbar.classList.add("sticky")
}
else {
navbar.classList.remove("sticky");
}
}
Hãy tự mình thử »