Cách thực hiện - Thay đổi lớp học
Tìm hiểu cách thay đổi tên lớp của một thành phần bằng JavaScript.
Thay đổi lớp
Thay đổi lớp của phần tử <div> từ "mystyle" thành "newone":
Ví dụ
<div id="myDIV" class="mystyle">
This is a DIV element.
</div>
<script>
function myFunction() {
const element =
document.getElementById("myDIV"); // Get the DIV element
element.classList.remove("mystyle"); // Remove mystyle class from DIV
element.classList.add("newone"); // Add newone class to DIV
}
</script>
Hãy tự mình thử »Mẹo: Đồng thời xem Cách chuyển đổi lớp A .
Mẹo: Tìm hiểu thêm về thuộc tính classList trong Tài liệu tham khảo JavaScript của chúng tôi.