Overview
In this lesson, you will learn to interact with and manipulate HTML elements using JavaScript. These objectives outline the skills and knowledge you will gain and serve as a checklist for your progress and assessment readiness.
Learning Objectives
1. Compare and Contrast NodeList and HTMLCollection
NodeList: A collection of nodes, including elements, text nodes, and comments, retrieved by methods like querySelectorAll(). It can be static or live depending on the method used.
HTMLCollection: A collection of HTML elements only, retrieved by methods like getElementsByTagName(). It is always live, meaning it updates as the DOM changes.
2. Select Elements by Attributes or Tags
// Select by tag
const paragraphs = document.querySelectorAll('p');
// Select by attribute
const buttons = document.querySelectorAll('[data-action="save"]');
3. Add or Remove Attributes
const element = document.querySelector('img');
// Add an attribute
element.setAttribute('alt', 'Descriptive text');
// Remove an attribute
element.removeAttribute('alt');
4. Get Children of a Parent Element
const parent = document.querySelector('ul');
const children = parent.children; // HTMLCollection of elements
5. Create or Remove Elements
// Create an element
const newDiv = document.createElement('div');
newDiv.textContent = 'Hello, World!';
// Remove an element
const elementToRemove = document.querySelector('#to-be-removed');
elementToRemove.remove();
6. Append a Child to a Parent
const parent = document.querySelector('#parent');
const child = document.createElement('span');
child.textContent = 'I am a child';
parent.appendChild(child);
7. Construct Elements with innerHTML
const container = document.querySelector('#container');
container.innerHTML = 'This is a dynamically created paragraph.
';
8. Compare innerHTML and innerText
innerHTML: Sets or retrieves the HTML content of an element. Use it for creating or updating HTML structures.
innerText: Retrieves or sets the visible text within an element. Use it when dealing with text content only.
9. Add or Remove Inline CSS
const element = document.querySelector('div');
// Add inline style
element.style.backgroundColor = 'blue';
// Remove inline style
element.style.backgroundColor = '';
10. Manipulate DOM Using Fetch Response
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
const container = document.querySelector('#data-container');
data.items.forEach(item => {
const div = document.createElement('div');
div.textContent = item.name;
container.appendChild(div);
});
});
Conclusion
Mastering these techniques will empower you to build dynamic and interactive web pages by effectively manipulating DOM elements. Use this checklist to practice and review each skill.