JS DOM Collections 🎯

beginner
17 min

JS DOM Collections 🎯

Welcome to our comprehensive guide on JavaScript (JS) DOM Collections! This tutorial is designed to help beginners and intermediates understand and master the art of manipulating HTML documents using JavaScript.

What are DOM Collections? 📝

In simple terms, DOM Collections are groups of elements that can be accessed and manipulated using JavaScript. They provide a convenient way to interact with HTML documents and dynamically change their content, structure, and behavior.

The Document Object Model (DOM) 📝

Before diving into DOM Collections, let's briefly understand the Document Object Model (DOM). The DOM is a programming interface for HTML and XML documents that allows you to access, manipulate, and navigate through the content of a document.

Basic DOM Collections 🎯

The document Object

The document object represents the entire HTML document. It's the starting point for accessing any other element in the document.

javascript
console.log(document);

The getElementById Method

This method allows you to access a specific element in the document using its id attribute.

html
<div id="myDiv">Hello World!</div>
javascript
const myDiv = document.getElementById('myDiv'); console.log(myDiv);

The getElementsByTagName Method

This method returns a collection of all elements with a specific tag name.

html
<ul id="myList"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul>
javascript
const myList = document.getElementsByTagName('li'); console.log(myList);

The getElementsByClassName Method

This method returns a collection of all elements with a specific class name.

html
<div class="myClass">Content</div>
javascript
const myClass = document.getElementsByClassName('myClass'); console.log(myClass);

Manipulating DOM Collections 🎯

Changing Content

You can change the content of an element by accessing its textContent or innerHTML property.

html
<div id="myDiv">Original Content</div>
javascript
const myDiv = document.getElementById('myDiv'); myDiv.textContent = 'New Content'; myDiv.innerHTML = '<strong>New Content</strong>';

Adding Elements

You can add new elements to the document using the createElement method and appending them using the appendChild method.

javascript
const newDiv = document.createElement('div'); newDiv.textContent = 'New Division'; const myDiv = document.getElementById('myDiv'); myDiv.appendChild(newDiv);

Quiz 🎯

Quick Quiz
Question 1 of 1

What does the `document` object represent in JavaScript?

Quick Quiz
Question 1 of 1

Which method returns a collection of all elements with a specific class name?