Hướng dẫn filter htmlcollection - lọc htmlcollection

Xin chào, tôi có vấn đề với việc lọc bộ sưu tập HTML. Tôi đã thu được danh sách các lớp là bộ sưu tập HTML. Một trong những lớp có lớp .Active. Tôi cần xóa tất cả các lớp khác khỏi danh sách này và chỉ để lại một lớp tiếp theo sau khi hoạt động. Xin vui lòng làm thế nào để làm điều đó?

Ví dụ về danh sách của tôi:

HTMLCollection []
0: div.chapter-list-item.seen
1: div.chapter-list-item.seen
2: div.chapter-list-item.seen
3: div.chapter-list-item.seen
4: div.chapter-list-item.active.seen
5: div.chapter-list-item.seen
6: div.chapter-list-item.seen
7: div.chapter-list-item.seen
8: div.chapter-list-item.

Mã của tôi:

let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
let activeChapter = document.getElementsByClassName["active"];
console.log[activeChapter];
console.log[allChaptersItems];

Maik Lowrey

12.3k4 Huy hiệu vàng19 Huy hiệu bạc53 Huy hiệu Đồng4 gold badges19 silver badges53 bronze badges

Hỏi ngày 21 tháng 10 năm 2020 lúc 6:10Oct 21, 2020 at 6:10

Bạn có thể truy vấn trực tiếp để lấy các mục bạn muốn sử dụng bộ chọn :not[] để ngăn các mục phù hợp mà bạn không muốn:

const chapters = document.querySelectorAll[".chapter-list-item:not[.active]"];

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
One
Two
Three
Four

Lưu ý rằng

let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
let activeChapter = document.getElementsByClassName["active"];
console.log[activeChapter];
console.log[allChaptersItems];
0 trả về một Nodelist, thay vì một htmlcollection. Sự khác biệt là HTMLCollection trực tiếp và sẽ thay đổi với những thay đổi đối với DOM, trong khi Nodelist thì không. Để giải thích đầy đủ, hãy xem sự khác biệt giữa HTMLCollection, Nodelist và mảng các đối tượng cả hai nút và htmlCollection là các đối tượng giống như mảng và có thể được xử lý giống nhau trong hầu hết các trường hợp.

Tuy nhiên, nếu bạn đã có một số yếu tố và muốn lọc chúng, bạn có thể chuyển đổi thành mảng và sau đó sử dụng

let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
let activeChapter = document.getElementsByClassName["active"];
console.log[activeChapter];
console.log[allChaptersItems];
1 để kiểm tra xem lớp "hoạt động" không có trong danh sách các lớp sử dụng
let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
let activeChapter = document.getElementsByClassName["active"];
console.log[activeChapter];
console.log[allChaptersItems];
2:

const existingElements = document.querySelectorAll[".chapter-list-item"];

const chapters = Array.from[existingElements]
  .filter[chapter => !chapter.classList.contains["active"]]

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
One
Two
Three
Four

Đã trả lời ngày 21 tháng 10 năm 2020 lúc 6:22Oct 21, 2020 at 6:22

VlazvlazVLAZ

24.7K9 Huy hiệu vàng47 Huy hiệu bạc62 Huy hiệu Đồng9 gold badges47 silver badges62 bronze badges

1

Trong bài viết này, mình sẽ giới thiệu cho các bạn cách thao tác với DOM bằng VanillaJS thông qua một ví dụ cụ thể. Vậy thì VanillaJS là gì? Nghe có vẻ nhưng là một thư viên, hay là một framework mới của Javascript. Hoàn toàn không phải, VanillaJS là một cái tên để chỉ việc sử dụng Javascript mà không cần bất cứ thư viên hỗ trợ nào, như Jquery,.. Mọi người sử dụng cái tên này giống như một sự đùa cợt để nhắc nhở những developer khác rằng ngày nay có nhiều thứ có thể được thực hiện mà không cần để sử dụng các thư viện của Javascript. Hay nói các khác VanillaJS chính là javascript thuần.

DOM là gì?

Khi một trang web được load, browser tạo ra Document Object Model [DOM]. DOM được xây dựng dưới dạng cây, các node của cây là các thẻ HTML. Ở trong DOM mỗi thẻ HTML được coi là một Objects, các attribute của thẻ HTML là thuộc tính của Objects. DOM còn cung cấp các methods để truy cập tới các thẻ HTML, và events cho các thẻ HTML.

Vậy tại sao nên học VanillaJS ?

Javascript càng ngày càng trở lên phổ biến, có rất nhiều library, framework ra đời. Để có thể dễ dàng nắm bắt được những library, framework mới, kiến thức cốt lõi về javascript là điều cần thiết. Trong những lúc phát triển sản phẩm, sẽ có đôi lúc cần sử dụng đến VanillaJS để xử lí một số trường hợp đặc biết mà library hoặc framework không thể xử lí được. Tất nhiên đây là trường hợp hiếm khi xảy ra, vì các library, framework ngày nay rất hịn hò rồi.

Có một trang web rất phổ biến hiện này, mà developer nào cũng biết đó là github.com. Hiện nay đội ngũ phát triển của github đã loại bỏ hoàn toàn jQuery khỏi trang web của họ và thay vào đó là chỉ sử dụng javascript thuần.

Ví dụ thực tế

Mình sẽ hướng dẫn mọi người làm một app đơn giản, chức năng của app sẽ bao gồm thêm task, tìm kiếm task, và xóa task. App này sẽ chỉ sử dụng HTML, CSS, Javascript, sẽ không sử dụng bất cứ thư viện hỗ trợ nào của Javascript. Thông qua ví dụ này, hy vọng mọi người sẽ nắm được cách sử dụng javascript thao tác với DOM, cách sử dụng Local Storage.

Chuẩn bị

Link source code: //github.com/l3duc/TaskList. Mọi người clone về và chạy thử xem app hoạt động như nào nhé.

Ok. Bắt tay vào làm thôi [go]

Chức năng thêm task

Đầu tiên, khai báo các biến UI

const form = document.querySelector['#task-form'];
const taskList = document.querySelector['.collection'];
const clearBtn = document.querySelector['.clear-tasks'];
const filter = document.querySelector['#filter'];
const taskInput = document.querySelector['#task'];

Có một số method phổ biến được dùng để chọn thẻ HTML trong DOM mà chúng ta muốn thao tác tới chúng.

  • document.getElementById[elementID]: Trả về thẻ HTML có
    let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
    let activeChapter = document.getElementsByClassName["active"];
    console.log[activeChapter];
    console.log[allChaptersItems];
    
    3 tương ứng.
  • document.querySelector[CSS selectors]: Trả về thẻ HTML đầu tiên ứng với CSS selectors.
  • document.getElementsByClassName[classname]: Trả về một HTMLCollection object, trong đó là những thẻ HTML có class tương ứng.
  • document.getElementByTagName[tagname]: Trả về một HTMLCollection object, trong đó là những thẻ HTML có tên thẻ tương ứng.
  • document.getQuerySelectorAll[CSS selectors]: Trả về một
    let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
    let activeChapter = document.getElementsByClassName["active"];
    console.log[activeChapter];
    console.log[allChaptersItems];
    
    4 object, trong đó là những thẻ HTML tương ứng với CSS selectors.

An HTMLCollection object is an array-like list of HTML elements.

A NodeList object is a list [collection] of nodes extracted from a document.

Tiếp theo khởi tạo một function, phụ trách việc load toàn bộ chức năng của app. Mình đặt tên là

let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
let activeChapter = document.getElementsByClassName["active"];
console.log[activeChapter];
console.log[allChaptersItems];
5.

loadEventListeners[];

function loadEventListeners[] {
    document.addEventListener['submit', addTask];
}

Ở đoạn code trên, khi người dùng submit một form, function

let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
let activeChapter = document.getElementsByClassName["active"];
console.log[activeChapter];
console.log[allChaptersItems];
6 sẽ được gọi, cụ thể ở đây mình có một form để người dùng thêm task. Có một số
let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
let activeChapter = document.getElementsByClassName["active"];
console.log[activeChapter];
console.log[allChaptersItems];
7 phổ biến khác phổ biến như
let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
let activeChapter = document.getElementsByClassName["active"];
console.log[activeChapter];
console.log[allChaptersItems];
8,
let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
let activeChapter = document.getElementsByClassName["active"];
console.log[activeChapter];
console.log[allChaptersItems];
9,
const chapters = document.querySelectorAll[".chapter-list-item:not[.active]"];

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
0,.. Các bạn có thể đọc thêm ở đây: //www.w3schools.com/jsref/dom_obj_event.asp

Sau đó, xây dựng function

let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
let activeChapter = document.getElementsByClassName["active"];
console.log[activeChapter];
console.log[allChaptersItems];
6:

function addTask[e] {
  if[taskInput.value === ''] {
    alert['Add a task'];
  }

  // Create li element
  const li = document.createElement['li'];
  // Add class
  li.className = 'collection-item';
  // Create text node and append to li
  li.appendChild[document.createTextNode[taskInput.value]];
  // Create new link element
  const link = document.createElement['a'];
  // Add class
  link.className = 'delete-item secondary-content';
  // Add icon html
  link.innerHTML = '';
  // Append the link to li
  li.appendChild[link];

  // Append li to ul
  taskList.appendChild[li];

  // Clear input
  taskInput.value = '';

  e.preventDefault[];
}

Funcntion

let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
let activeChapter = document.getElementsByClassName["active"];
console.log[activeChapter];
console.log[allChaptersItems];
6 nhận tham số truyền vào là
const chapters = document.querySelectorAll[".chapter-list-item:not[.active]"];

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
3, đây là một biến tham chiếu tới
const chapters = document.querySelectorAll[".chapter-list-item:not[.active]"];

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
4.
const chapters = document.querySelectorAll[".chapter-list-item:not[.active]"];

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
5 hỗ trợ nhiều
const chapters = document.querySelectorAll[".chapter-list-item:not[.active]"];

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
6 xử lí sự kiện trong DOM.
const chapters = document.querySelectorAll[".chapter-list-item:not[.active]"];

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
7 hủy một sự kiện, đồng nghĩa với việc những
const chapters = document.querySelectorAll[".chapter-list-item:not[.active]"];

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
8 ở trong sự kiện đó sẽ không xảy ra. Cụ thể, khi người dùng submit form,
const chapters = document.querySelectorAll[".chapter-list-item:not[.active]"];

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
9 sẽ ngăn chặn gửi form lên Server.

Để có thể lấy dữ liệu người dùng nhập vào ô input, sử dụng thuộc tính

One
Two
Three
Four
0. Cũng có thể dùng
One
Two
Three
Four
0 để set giá trị cho ô input.

Tiếp theo tạo một thẻ

One
Two
Three
Four
2, bằng
One
Two
Three
Four
3, sau đó thêm class
One
Two
Three
Four
4 vào trong thẻ
One
Two
Three
Four
2 bằng
One
Two
Three
Four
6. Tiếp theo tạo một
One
Two
Three
Four
7 bằng
One
Two
Three
Four
8, cụ thể ở đây mình tạo một
One
Two
Three
Four
7 có giá trị là input người dùng nhập vào. Sau đó thêm text node đó vào thẻ
const existingElements = document.querySelectorAll[".chapter-list-item"];

const chapters = Array.from[existingElements]
  .filter[chapter => !chapter.classList.contains["active"]]

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
0 bằng
const existingElements = document.querySelectorAll[".chapter-list-item"];

const chapters = Array.from[existingElements]
  .filter[chapter => !chapter.classList.contains["active"]]

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
1.

Tiếp theo tạo một thẻ

const existingElements = document.querySelectorAll[".chapter-list-item"];

const chapters = Array.from[existingElements]
  .filter[chapter => !chapter.classList.contains["active"]]

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
2 bằng
const existingElements = document.querySelectorAll[".chapter-list-item"];

const chapters = Array.from[existingElements]
  .filter[chapter => !chapter.classList.contains["active"]]

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
3. Thêm class vào thẻ
const existingElements = document.querySelectorAll[".chapter-list-item"];

const chapters = Array.from[existingElements]
  .filter[chapter => !chapter.classList.contains["active"]]

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
2,
const existingElements = document.querySelectorAll[".chapter-list-item"];

const chapters = Array.from[existingElements]
  .filter[chapter => !chapter.classList.contains["active"]]

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
5, thêm icon vào trong thẻ
const existingElements = document.querySelectorAll[".chapter-list-item"];

const chapters = Array.from[existingElements]
  .filter[chapter => !chapter.classList.contains["active"]]

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
2,
const existingElements = document.querySelectorAll[".chapter-list-item"];

const chapters = Array.from[existingElements]
  .filter[chapter => !chapter.classList.contains["active"]]

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
7

Thêm thẻ

const existingElements = document.querySelectorAll[".chapter-list-item"];

const chapters = Array.from[existingElements]
  .filter[chapter => !chapter.classList.contains["active"]]

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
2 vào trong thẻ
const existingElements = document.querySelectorAll[".chapter-list-item"];

const chapters = Array.from[existingElements]
  .filter[chapter => !chapter.classList.contains["active"]]

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
0 bằng method
One
Two
Three
Four
0,
One
Two
Three
Four
1.

Thêm thẻ

const existingElements = document.querySelectorAll[".chapter-list-item"];

const chapters = Array.from[existingElements]
  .filter[chapter => !chapter.classList.contains["active"]]

console.log["Found elements:"]
for [const chapter of chapters] {
  console.log[chapter.textContent, chapter.className]
}
0 vào thẻ
One
Two
Three
Four
3,
One
Two
Three
Four
4. Khi người dùng thêm một task thành công, sẽ xóa input người dùng vừa nhập vào ô input, bằng cách set value của ô input là một chuỗi rỗng.
One
Two
Three
Four
5.

Mình vừa xây dựng xong function

let allChaptersItems= document.getElementsByClassName["chapter-list-item"];
let activeChapter = document.getElementsByClassName["active"];
console.log[activeChapter];
console.log[allChaptersItems];
6

Kết luận

Ở trong bài tiếp theo, mình sẽ hướng dẫn mọi người xây dựng những chức năng còn lại của app. Hy vọng sẽ giúp mọi người biết cách thao tác với DOM bằng cách chỉ sử dụng VanillaJS.

Happy coding

Bài Viết Liên Quan

Chủ Đề