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

Cách xóa classList của phần tử trong JavaScript

Để xóa một class khỏi classList của phần tử, bạn có thể sử dụng phương thức remove().

Ví dụ

Dưới đây là mã nguồn minh họa:

<!DOCTYPE html> <html lang="en"> <head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Document</title> </head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <style>    .removeClass {       color: red;    } </style> <body> <p id="remove" class="removeClass">Javascript Tutorial</p> </div> <button onclick="removeClassName()">Remove</button> </body> <script>    function removeClassName() {       const element = document.getElementById("remove");       element.classList.remove("removeClass");    } </script> </html>

Để chạy chương trình trên, lưu file với tên bất kỳ (ví dụ index.html). Chuột phải vào file và chọn Open with Live Server trong trình soạn thảo VS Code.

Kết quả đầu ra ban đầu:

Cách xóa classList của phần tử trong JavaScript

Sau khi nhấn nút Remove, class removeClass bị xóa và chữ không còn màu đỏ:

Kết quả

Cách xóa classList của phần tử trong JavaScript