Javascript DOM Manipulation

JS Code Snippets DOM Manipulation


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.


<!DOCTYPE html>
        <title>DOM Manipulation</title>
    <script src="code.js"></script>
            <div id="listWrapper" class="section">
                <ul id="itemList">
                    <li>list item 1</li>
                    <li>list item 2</li>
                    <li>list item 3</li>

            <div id="textWrapper" class="section">
                <p id="text">Just some text.</p>

            <div id="removeMe" class="section">
                <p>Remove me.</p>

            <div class="section">
                <img id="thisPost" src="js code snippets.png" width="250">

            <div class="section">
                <div id="coloredDiv" style="background-color: blue; width: 100px; height: 100px;"></div>
//Run this when the HTML gets loaded.
window.onload = () => {
    //Getting elements//////////////////////////////////////////

    //Get element by tag.
    let li_elements = document.getElementsByTagName("li");
    //Get element by id.
    let text_element = document.getElementById("text");
    //Get elements by class.
    let sections = document.getElementsByClassName("section");
    //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,
    //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.
    //Get existing list.
    let itemsList = document.getElementById("itemList");
    //Add new li to existing list.

Resulting output:


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger