JavaScript: DOM Manipulation
Overview
One of the key skill sets of any frontend web developer is the ability to manipulate the document content using the DOM. The DOM is the outline of the HTML and content nodes. The purpose of this activity is to strengthen our understanding of the DOM and to change or manipulate the document using JavaScript. Learning JavaScript establishes a strong foundation upon which to build, regardless of any frontend JavaScript framework evolutions.
Prepare
- Read: 📃 Manipulating documents - MDN.
Note that the 📑 Active learning: A dynamic shopping list example found at the end of the MDN article will help you complete this activity.
- Review: Common DOM manipulation concepts/use cases.
- To select an HTML element from the document - using the querySelector method.
This line of code selects the first instance of an article element from the document and assigns the element as a reference to the variable namedarticle
.const article = document.querySelector('article');
- To change the innerHTML property of an existing element.
This line of code uses an existing variable that has already selected an element and changes its innerHTML property value.article.innerHTML = 'innerHTML supports <strong>HTML</strong> tags. The textContent property does not.';
- To change the inline CSS style of an element.
This line of code changes the text-align CSS property of the selected element.article.style.textAlign = 'right';
- To change an attribute of an element.
This line of code adds and attribute class to the element and gives it a value.article.setAttribute('class', 'active');
When adding a class, it's more common and recommended to use theclassList
property.article.classList.add('active');
- To create an element.
This line of code creates a new <p> element and stores it in the variable named paragraph.const paragraph = document.createElement('p');
- To append an element with additional content or elements.
These lines of code add content to the end of the article element.article.appendChild(paragraph); article.append('Hello World Addition!');
- To remove an element from the document.
These lines of code remove the paragraph from the article and then, the article itself.article.removeChild(paragraph); article.remove();
- To select an HTML element from the document - using the querySelector method.
Activity Instructions
The group collaboration assignment this week will have you build an application which allows users to enter their favorite Book of Mormon chapters and display them on a list that is updated automatically on the screen. Entries can be deleted from the displayed list by the user.
Submission
- There is no submission for this learning activity.
Additional Resources
- 🎦 DOM Manipulation – by Web Dev Simplified – 14 key techniques in summary demonstration format. Take special note of the concept of datasets.