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

Thêm class odd/even cho HTML với JavaScript (CSS nth-child)

Thay vì dùng JavaScript để thêm class odd/even, **CSS pseudo-class :nth-child() là cách chuẩn, hiệu năng tốt, không cần JS**.

CSS :nth-child() - Khuyên dùng:

/* Phần tử con lẻ (1, 3, 5...) */
.element:nth-child(odd) { background: #f0f0f0; }

/* Phần tử con chẵn (2, 4, 6...) */
.element:nth-child(even) { background: #fff; }

/* Công thức: an+b */
.element:nth-child(3n) { }      /* 3, 6, 9... */
.element:nth-child(2n+1) { }    /* odd */
.element:nth-child(-n+3) { }    /* 3 đầu tiên */

Ví dụ chỉ dùng CSS (Không cần JS)

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS nth-child odd/even</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
    .subjects { display: flex; flex-direction: column; gap: 8px; max-width: 300px; }
    .subjectName { padding: 12px; background: #f5f5f5; border-radius: 4px; }
    
    /* CSS only - no JS needed! */
    .subjectName:nth-child(odd) { color: blue; background: #e3f2fd; }
    .subjectName:nth-child(even) { color: purple; background: #f3e5f5; }
  </style>
</head>
<body>
  <h1>CSS :nth-child(odd/even) - Không cần JavaScript</h1>
  <section class="subjects">
    <article class="subjectName">MongoDB</article>
    <article class="subjectName">JavaScript</article>
    <article class="subjectName">Java</article>
    <article class="subjectName">MySQL</article>
  </section>
  <p>Thử thêm/bớt article - màu tự động cập nhật!</p>
</body>
</html>

Kết quả

MongoDB (1 - odd) → Xanh dương

JavaScript (2 - even) → Tím

Java (3 - odd) → Xanh dương

MySQL (4 - even) → Tím

Nếu BẮT BUỘC dùng JavaScript (ví dụ: logic phức tạp, không thể dùng CSS):

<script>
const items = document.querySelectorAll('.subjectName');
items.forEach((item, index) => {
  // index 0-based: 0,1,2,3 -> odd/even ngược với nth-child (1-based)
  if ((index + 1) % 2 === 1) {
    item.classList.add('odd');
  } else {
    item.classList.add('even');
  }
});
</script>

So sánh CSS vs JS:

Tiêu chíCSS :nth-childJavaScript classList
Hiệu năngNative browser, rất nhanhCần DOM manipulation, chậm hơn
Động (dynamic)Tự động cập nhật khi DOM thay đổiCần chạy lại khi DOM thay đổi
Separation of concernsTách style/logicTrộn style vào logic
SpecificityDễ kiểm soátClass có thể bị override
Browser supportTất cả (IE9+)Tất cả

Các pseudo-class hữu ích khác:

:first-child        /* Phần tử con đầu tiên */
:last-child         /* Phần tử con cuối cùng */
:only-child         /* Con duy nhất của parent */
:first-of-type      /* Đầu tiên theo tag type */
:nth-of-type(odd)   /* Chỉ tính cùng tag type */
:not(.class)        /* Loại trừ selector */

Kết luận: Luôn ưu tiên CSS :nth-child(odd/even) cho zebra striping. Chỉ dùng JS khi logic không thể biểu diễn bằng CSS.