JavaScript - DOM Collections

Hello there, aspiring programmers! Today, we're going to dive into the fascinating world of DOM Collections in JavaScript. Don't worry if you're new to programming – I'll guide you through this journey step by step, just as I've done for countless students over my years of teaching. So, grab a cup of coffee (or your favorite beverage), and let's get started!

JavaScript - DOM Collections

The HTMLCollection Object

Imagine you're at a library, and you want to find all the books about JavaScript. The librarian gives you a special cart containing all these books. In the world of web development, this cart is like an HTMLCollection – a collection of HTML elements that we can work with using JavaScript.

What is an HTMLCollection?

An HTMLCollection is a list-like object that represents a collection of HTML elements on a web page. It's "live," meaning it automatically updates when the underlying document changes.

Let's look at a simple example:

<div class="book">JavaScript Basics</div>
<div class="book">Advanced JavaScript</div>
<div class="book">DOM Manipulation</div>

<script>
let books = document.getElementsByClassName('book');
console.log(books);
console.log(books.length); // Outputs: 3
</script>

In this example, books is an HTMLCollection containing all elements with the class "book". The length property tells us how many elements are in the collection.

Accessing Elements in an HTMLCollection

You can access elements in an HTMLCollection just like you would with an array:

console.log(books[0].innerText); // Outputs: "JavaScript Basics"
console.log(books[1].innerText); // Outputs: "Advanced JavaScript"
console.log(books[2].innerText); // Outputs: "DOM Manipulation"

However, remember that an HTMLCollection is not exactly an array. It's array-like, but it doesn't have all the methods that arrays have.

Looping Through an HTMLCollection

To iterate over all elements in an HTMLCollection, you can use a for loop:

for (let i = 0; i < books.length; i++) {
console.log(books[i].innerText);
}

Or, if you prefer a more modern approach, you can convert the HTMLCollection to an array and use array methods:

Array.from(books).forEach(book => {
console.log(book.innerText);
});

Collections of document Object and DOM Elements

Now that we understand HTMLCollection, let's explore some common ways to create collections of DOM elements.

document.getElementsByTagName()

This method returns an HTMLCollection of elements with the specified tag name.

<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>

<script>
let paragraphs = document.getElementsByTagName('p');
console.log(paragraphs.length); // Outputs: 3

for (let i = 0; i < paragraphs.length; i++) {
console.log(paragraphs[i].innerText);
}
</script>

document.getElementsByClassName()

We've seen this before, but let's dive a little deeper:

<div class="fruit">Apple</div>
<div class="fruit">Banana</div>
<div class="fruit">Orange</div>

<script>
let fruits = document.getElementsByClassName('fruit');
console.log(fruits.length); // Outputs: 3

Array.from(fruits).forEach(fruit => {
console.log(fruit.innerText);
});
</script>

document.querySelectorAll()

This powerful method returns a NodeList (which is similar to an HTMLCollection) of all elements matching a CSS selector:

<ul>
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>

<script>
let items = document.querySelectorAll('ul .item');
console.log(items.length); // Outputs: 3

items.forEach(item => {
console.log(item.innerText);
});
</script>

Note that unlike HTMLCollection, NodeList returned by querySelectorAll() is not live and has a forEach method built-in.

Comparison of Collection Methods

Here's a handy table summarizing the collection methods we've discussed:

Method Returns Live? Use Case
getElementsByTagName() HTMLCollection Yes When you need elements of a specific tag
getElementsByClassName() HTMLCollection Yes When you need elements with a specific class
querySelectorAll() NodeList No When you need elements matching a CSS selector

Remember, "live" means the collection updates automatically when the DOM changes.

Conclusion

And there you have it, dear students! We've journeyed through the land of DOM Collections, from HTMLCollection to various methods of gathering DOM elements. These tools are fundamental to manipulating web pages with JavaScript, allowing you to select and modify elements with ease.

As you practice with these concepts, you'll find yourself becoming more comfortable with DOM manipulation. It's like learning to play an instrument – at first, it might seem challenging, but with practice, you'll be creating beautiful web symphonies in no time!

Remember, the key to mastering programming is practice and curiosity. Don't be afraid to experiment with these methods, try out different scenarios, and most importantly, have fun while coding!

Until next time, happy coding!

繁體中文翻譯:

JavaScript - DOM Collections

你好,有志於成為程序員的各位!今天,我們將要深入探索JavaScript中DOM Collections的迷人世界。如果你是編程新手,別擔心——我會一步步引導你走過這個旅程,正如我這些年來對無數學生所做的一樣。所以,來一杯咖啡(或是你喜歡的飲料),我們開始吧!

The HTMLCollection Object

想像你在一個圖書館,你想找到所有關於JavaScript的書。圖書管理員給你一個特別的推車,裡面裝滿了這些書。在網頁開發的世界中,這個推車就像是HTMLCollection——一個可以用JavaScript操作的HTML元素集合。

What is an HTMLCollection?

HTMLCollection是一個類似於列表的對象,它代表著網頁上的HTML元素集合。它是“實時的”,意味著當底層文件變化時,它會自動更新。

讓我們看一個簡單的例子:

<div class="book">JavaScript Basics</div>
<div class="book">Advanced JavaScript</div>
<div class="book">DOM Manipulation</div>

<script>
let books = document.getElementsByClassName('book');
console.log(books);
console.log(books.length); // 輸出: 3
</script>

在這個例子中,books是一個包含所有類別為"book"的元素的HTMLCollection。length屬性告訴我們集合中有多少個元素。

Accessing Elements in an HTMLCollection

你可以像操作數組一樣訪問HTMLCollection中的元素:

console.log(books[0].innerText); // 輸出: "JavaScript Basics"
console.log(books[1].innerText); // 輸出: "Advanced JavaScript"
console.log(books[2].innerText); // 輸出: "DOM Manipulation"

然而,記住HTMLCollection並不完全是數組。它是類似於數組的,但它沒有數組所有的方 法。

Looping Through an HTMLCollection

要遍歷HTMLCollection中的所有元素,你可以使用for循環:

for (let i = 0; i < books.length; i++) {
console.log(books[i].innerText);
}

或者,如果你喜歡更現代的方法,你可以將HTMLCollection轉換為數組並使用數組方法:

Array.from(books).forEach(book => {
console.log(book.innerText);
});

Collections of document Object and DOM Elements

既然我們理解了HTMLCollection,讓我們探討一些常見的創建DOM元素集合的方法。

document.getElementsByTagName()

這個方法返回一個包含指定標籤名元素的HTMLCollection。

<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>

<script>
let paragraphs = document.getElementsByTagName('p');
console.log(paragraphs.length); // 輸出: 3

for (let i = 0; i < paragraphs.length; i++) {
console.log(paragraphs[i].innerText);
}
</script>

document.getElementsByClassName()

我們之前見過這個,但讓我們更深入地了解:

<div class="fruit">Apple</div>
<div class="fruit">Banana</div>
<div class="fruit">Orange</div>

<script>
let fruits = document.getElementsByClassName('fruit');
console.log(fruits.length); // 輸出: 3

Array.from(fruits).forEach(fruit => {
console.log(fruit.innerText);
});
</script>

document.querySelectorAll()

這個強大的方法返回一個與CSS選擇器匹配的所有元素的NodeList(類似於HTMLCollection):

<ul>
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>

<script>
let items = document.querySelectorAll('ul .item');
console.log(items.length); // 輸出: 3

items.forEach(item => {
console.log(item.innerText);
});
</script>

注意,與HTMLCollection不同的是,由querySelectorAll()返回的NodeList不是實時的,並且內置了forEach方法。

Comparison of Collection Methods

這裡有一個方便的表格,總結了我們討論過的集合方法:

方法 返回 實時? 使用場景
getElementsByTagName() HTMLCollection 當你需要特定標籤的元素時
getElementsByClassName() HTMLCollection 當你需要具有特定類的元素時
querySelectorAll() NodeList 當你需要匹配CSS選擇器的元素時

記住,“實時”意味著集合會在DOM變化時自動更新。

Conclusion

親愛的學生們,這就是今天的内容!我們一起穿越了DOM Collections的土地,從HTMLCollection到各種收集DOM元素的方法。這些工具對於使用JavaScript操作網頁是基礎的,它們讓你可以輕鬆地選擇和修改元素。

當你實踐這些概念時,你會發現自己越來越熟練於DOM操作。這就像學習演奏樂器一樣——起初,它可能看起來很具挑戰性,但隨著練習,你將能夠很快創作出美麗的網頁交響曲!

記住,精通編程的關鍵是練習和好奇心。不要害怕嘗試這些方法,嘗試不同的場景,最重要的是,編程時要玩得開心!

下次見,快樂編程!

Credits: Image by storyset