About
In this code snippet, we’ll learn how to manipulate the DOM with Javascript.
When you open up a web page the browser will parse the HTML and CSS. Then it will build a DOM(data object model) from the parsed data. Finally, it will render it to display the web page.
Javascript can be used to dynamically change the DOM. We can do that by getting elements(by tag, id or class) and then modifying, adding or removing them.
Let’s see the code example below.
Code:
index.html
<!DOCTYPE html> <html> <head> <title>DOM Manipulation</title> </head> <script src="code.js"></script> <body> <div> <div id="listWrapper" class="section"> <ul id="itemList"> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ul> </div> <div id="textWrapper" class="section"> <p id="text">Just some text.</p> </div> <div id="removeMe" class="section"> <p>Remove me.</p> </div> <div class="section"> <img id="thisPost" src="js code snippets.png" width="250"> </div> <div class="section"> <div id="coloredDiv" style="background-color: blue; width: 100px; height: 100px;"></div> </div> </div> </body> </html>
code.js
//Run this when the HTML gets loaded. window.onload = () => { //Getting elements////////////////////////////////////////// //Get element by tag. let li_elements = document.getElementsByTagName("li"); console.log(li_elements); //Get element by id. let text_element = document.getElementById("text"); console.log(text_element); //Get elements by class. let sections = document.getElementsByClassName("section"); console.log(sections); //////////////////////////////////////////////////////////// //Modify elements/////////////////////////////////////////// //Change CSS. document.getElementById("coloredDiv").style.backgroundColor = "red"; //Change HTML. document.getElementById("textWrapper").innerHTML = "<h1 id='postTitle'>DOM Manipulation</h1>"; //Change attribute. document.getElementById("thisPost").src = "JS Code Snippets DOM Manipulation.png"; //////////////////////////////////////////////////////////// //Add/remove elements/////////////////////////////////////// //Remove element, document.getElementById("removeMe").remove(); //Create and add new element//////////////////////////////// //Create new li element. const newLiElement = document.createElement("li"); //Create new text content. const newLiText = document.createTextNode("list item 4"); //Add text to newly created li element. newLiElement.appendChild(newLiText); //Get existing list. let itemsList = document.getElementById("itemList"); //Add new li to existing list. itemsList.appendChild(newLiElement); //////////////////////////////////////////////////////////// }