Kiểm tra class tồn tại trên element đơn giản và nhanh với phương thức contains() của JavaScript classList property.
Xem công thức chung dùng classList.contains() rồi xem use case thực tế.
Công thức classList.contains()
var element = document.querySelector("selector") element.classList.contains("class")
Trong ví dụ chung dùng querySelector() tìm target element qua selector name. Selector có thể class selector, element selector, hoặc loại khác.
Gán element tìm được bằng querySelector() cho biến element khai báo.
Gắn phương thức contains() của classList property cho element qua biến tham chiếu. Bên trong argument contains() (trong ngoặc) chỉ định tên 'class' muốn kiểm tra tồn tại.
Ví dụ chung nhàm chán, làm thực tế!
News Feed Không Rối Rắm
Lọc với classList.contains()
— use case thực tế

Bạn truy cập website news feed hỗn hợp nhiều category. Nhưng bạn chỉ quan tâm đọc về công nghệ.
News feed rối rắm là冒渎. Lọc bỏ các category khác, dùng classList.contains().
Thêm HTML để có content làm việc. Style nhanh, sang JavaScript.
HTML cho news feed
<div class="wrapper"> <h1>Newsfeed</h1> <div class="news-feed"> <h3 class="headline"> <a class="link category-health" href="#">Health</a> </h3> <h3 class="headline"> <a class="link category-finances" href="#">Finances</a> </h3> <h3 class="headline"> <a class="link category-politics" href="#">Politics</a> </h3> <h3 class="headline"> <a class="link category-nature" href="#">Nature</a> </h3> <h3 class="headline"> <a class="link category-humor" href="#">Humor</a> </h3> <h3 class="headline"> <a class="link category-weather" href="#">Weather</a> </h3> <h3 class="headline"> <a class="link category-technology" href="#">Technology</a> </h3> <h3 class="headline"> <a class="link category-sports" href="#">Sports</a> </h3> </div> <div class="fixed-container"> <span>Filter:</span> <button class="btn-technology">Technology</button> </div> </div> <!-- wrapper -->
Nội dung HTML:
- Headline lớn.
- News feed các category khác nhau.
- Ngoài news feed, button Technology. Nút này toggle (ẩn/hiện) tất cả topic non-technology.
Rõ ràng news feed ví dụ chỉ vài item (minh họa), không rối. Nhưng mixed news feed thật có hàng loạt bài từ mỗi category, ngập feed. Lúc đó nút lọc hữu ích.
CSS Styling
CSS dưới đây cosmetic và tùy chọn, trừ class .js-hide, helper class dùng với JS đoạn sau.
body { font-family: "Source Sans Pro", "Helvetica", "Sans-Serif"; } .wrapper { position: relative; padding-left: 1rem; padding-right: 1rem; margin: 2rem auto; max-width: 50em; } .news-feed { border: 1px solid #eee; max-height: 256px; overflow-y: scroll; } .headline { font-size: 1.25rem; padding: 0.25rem 1.5rem; } .link { color: #252525; text-decoration: none; } .fixed-container { position: fixed; bottom: 0; left: 0; padding: 1.5rem; } .btn-technology { cursor: pointer; font-size: 1rem; padding: 0.5rem 1rem; margin-top: 2rem; margin-left: 1rem; border-radius: 4px; border: 1px solid #82b97e; outline: none; } .js-hide { display: none; }
Chắc chắn thêm class .js-hide vào stylesheet, sang JavaScript!
JavaScript
Copy paste code sau vào file JS. Giải thích ngay dưới.
var btnTechnology = document.querySelector(".btn-technology") var allNewsCategories = document.querySelectorAll(".news-feed .link") function showCategoryTechnology() { for (var i = 0; i < allNewsCategories.length; i++) { if (!allNewsCategories[i].classList.contains("category-technology")) { allNewsCategories[i].parentElement.classList.toggle("js-hide") } } } btnTechnology.addEventListener("click", showCategoryTechnology)
Cách code JavaScript hoạt động
- Dùng
querySelector()lấy button Technology qua class.btn-technology, làm trigger cho function lọc sau. Gán cho biếnbtn-technology. - Dùng
querySelectorAll()lấy tất cả item News Feed (.news-feed) chọn link từng item bằng class (.link). Gán tất cả link news item cho biếnallNewsCategories. - Tạo function
showCategoryTechnology() {..}gọi khi button Technology click. - Bên trong function body, loop qua tất cả item () trong News Feed lưu vào mảng
[i] - Bên trong loop, thêm if statement điều kiện: "nếu item bất kỳ trong list vừa lặp không chứa class
.category-technology— chạy classList.toggle với class.js-hidetrên item đó. - Dòng cuối, gắn
addEventListener()cho button element. Lắng nghe event 'click'. Khi click, gọishowCategoryTechnology(), chạy toàn bộ code block làm toggle feature.
Ký hiệu ! (Logical Operator) trước allNewsCategories[i] xử lý phần "not" của if. Nếu bỏ ! code làm ngược lại.
Cũng có thể dùng classList.remove() xóa item không muốn. Nhưng đa số trường hợp nên cho user tùy chọn ẩn/hiện, đó là classList.toggle().