Open In App

How to return HTML or build HTML using JavaScript ?

Last Updated : 15 Feb, 2023
Like Article

JavaScript is very powerful and with it, we can build dynamic web content and add many features to a web application.  With HTML, we create the structure of the web page and the same thing can also be done with JavaScript. 

There are a few JavaScript methods called as createElement(), appendChild() with which we can add nodes to the DOM tree on the fly. 

Example 1: Creating a div element

Say you just want to create a div element, then for that below is the code snippet:

let div_element = document.createElement("div")

Example 2: Adding a child node to an HTML element

Say there’s a div with ID “divele”

<div id="divele"></div>

And you want to add a paragraph element inside div. Below is the code snippet


let div_elem = document.getElementById("divele")
let child_p_elem = document.createElement("p")

This code snippet is adding a paragraph element inside div with the help of appendChild() method.

Example 3: Removing a child node of an HTML element

Consider an unordered list having 3 list items in it.  And you want to remove the first child <li> element in it.


<ul id="ulele">

Using the removeChild() method, we can remove the first <li> child from the unordered list:


let ul_ele = document.getElementById("ulele")
// 0 represents the first child

Example 4: To access all the child elements of a parent HTML element 

Now, to access all the child elements of the div having id “divele”, we will use the childNodes() method which will return the required child nodes.


let div_ele = document.getElementById("divele")
// Returns an array of child nodes
// contained inside the parent node
let div_ele_childs = div_ele.childNodes 

Please find below the snapshot of the simple webpage that we are going to develop.

Complete Code:


    <div id="divele">
    <script type="text/javascript">
        let parentDiv = document.getElementById("divele")
        let heading = document.createElement("h1")
        let unordered_list = document.createElement("ul")
        unordered_list.setAttribute("id", "ulele")
  = "green"
        heading.textContent = "GeeksforGeeks"
        for (let i = 0; i < 4; i++) {
            let li_elem = document.createElement("li")
        unordered_list.childNodes[0].textContent = "Java"
        unordered_list.childNodes[1].textContent = "Python"
        unordered_list.childNodes[2].textContent = "Javascript"
        unordered_list.childNodes[3].textContent = "C#"


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads