Summary - DOM manipulation
Write a function that adds a new comment to a comment list using createElement and appendChild.
DOM manipulation summary
In this group you saw how to create and change elements. document.createElement('tag') makes a new element in memory; with appendChild you add it to the page. classList.add writes a class, setAttribute writes an attribute. innerHTML and insertAdjacentHTML parse an HTML string.
Now combine them: we will write a function that adds a new comment to a comment list.
Exercise Comment-adding function
Define a function named addComment. It takes one parameter: text. The function should create a new <li> element, assign text to its textContent, add the 'comment' class, and append it to the <ul> element whose id is comments.
Show example solution
function addComment(text) {
const item = document.createElement('li');
item.textContent = text;
item.classList.add('comment');
document.querySelector('#comments').appendChild(item);
}
Exercise Tag-adding function
Define a function named addTag. It takes one parameter: name. The function should create a new <span> element, assign name to its textContent, add the 'tag' class, and append it to the <div> element whose id is tags.
Show example solution
function addTag(name) {
const tag = document.createElement('span');
tag.textContent = name;
tag.classList.add('tag');
document.querySelector('#tags').appendChild(tag);
}
Test yourself
-
Match methods to their uses
- createElement
- Makes a new element
- appendChild
- Adds a child
- classList.add
- Adds a class
- setAttribute
- Writes an attribute
-
Append the new element to the list
const list = document.querySelector('#comments'); const item = document.createElement('li'); list.____(item);Show answer
const list = document.querySelector('#comments'); const item = document.createElement('li'); list.appendChild(item);