Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เช็คว่า Class มีอยู่บน Element หรือไม่ ด้วย JavaScript

เช็ค class บน element ใช้ classList.contains() method — เรียบง่ายและเร็ว

classList.contains() Formula

var element = document.querySelector("selector");
element.classList.contains("class");

querySelector() หา target element → assign variable element → attach classList.contains() ระบุ class name ใน argument

The Uncluttered News Feed — Practical Use Case

Filtering ด้วย classList.contains()

เช็คว่า Class มีอยู่บน Element หรือไม่ ด้วย JavaScript

News feed หลาย category อยากอ่านแค่ Technology

HTML 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>

CSS Styling

CSS cosmetic ทั้งหมด ยกเว้น .js-hide helper class สำหรับ JS:

.js-hide { display: none; }

JavaScript

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);

JS ทำงานอย่างไร

  • Grab Technology button .btn-technology → variable btnTechnology
  • querySelectorAll() grab all news feed links .link → allNewsCategories
  • Function showCategoryTechnology() เรียกตอนกดปุ่ม
  • Loop ทุก items ใน news feed store ใน array [i]
  • If statement: ถ้า item ไม่มี class .category-technology → toggle .js-hide บน parentElement
  • Attach addEventListener('click') ให้ปุ่ม เรียก function

! (Logical NOT) จัดการส่วน "ไม่" ใน if statement ลบ ! จะทำกลับกัน

ใช้ classList.remove() ลบได้ แต่ toggle() ให้ user hide/show ได้ดีกว่า

CodePen พร้อมโค้ดทั้งหมด

Resources