Notes

Adding and Removing Nodes (HTML Elements)

Edit on GitHub

Web Development
2 minutes

Creating new nodes

  • createElement() creates an HTML element
  • createTextNode() creates a text node
  • appendChild() appends (adds to the end) a node
  • insertBefore() prepends a node, opposite of .appendChild()
  • removeChild() removes a child node
  • replaceChild() replaces a child node
  • cloneNode() creates a copy of the node (You can clone a node before adding it for example)

Creating and adding

1let paragraph = document.createElement("p"); // create a paragraph (<p> element)
2
3// to add text to the <p> element, create a text node first
4let node1 = document.createTextNode("This is new paragraph i just added to the DOM");
5let node2 = document.createTextNode("This is the text i'm going to add before")
6
7paragraph.appendChild(node1); // add (append) the text node to the <p> element
 1// create a container <div> element
 2let container = document.createElement('div')
 3
 4// cerate two paragraph <p> elements
 5let para = document.createElement('p') // create a pragraph
 6let anotherPara = document.createElement('p') // create another paragraph
 7
 8// create some text nodes to add to <p> elements
 9let text1 = document.createTextNode('This is some text')
10let text2 = document.createTextNode('This is some more random text')
11
12// append text to paragraphs
13para.append(text1)
14anotherPara.append(text2)
15
16console.info(para) // <p>This is some text</p>
17console.info(anotherPara) // <p>This is some more random text</p>
18console.info(container) // <div></div>
19
20// append a paragraph to a div
21container.append(para)
22console.info(container) // <div><p>This is some text</p></div>
23
24// insert a paragraph before another paragraph in the div
25// parentNode.insertBefore(newNode, referenceNode) 
26container.insertBefore(anotherPara, para)
27console.info(container) // <div><p>This is some more random text</p><p>This is some text</p></div>

We have created the following HTML structure using JavaScript

1<div>
2  <p>
3    This is some more random text
4  </p>
5  <p>
6    This is some text
7  </p>
8</div>

Removing nodes

1let parent = document.getElementById("div1");
2let child = document.getElementById("p1");
3
4parent.removeChild(child);

Replacing nodes

1let para = document.createElement("p");
2let node = document.createTextNode("This is new.");
3para.appendChild(node);
4
5let parent = document.getElementById("div1");
6let child = document.getElementById("p1");
7parent.replaceChild(para, child);