In the previous videos and blogs, I showed you a couple of things with getting 1 or more HTML elements via Vanilla JavaScript. This time we are going to add and remove HTML elements to our page with Vanilla JavaScript. We are gonna use the createElement, createTextNode, appendChild & removeChild methods for it.

If your not a video person, please scroll down for the written version 😉

Add element to body

First, let’s add an HTML element to our page via Vanilla JavaScript.

You create an element with the method createElement. Then create a text inside of it with the methodcreateTextNode.

Combine them with the method appendChild. After that, use the same method to add the div to the body.

Check the example code below!

HTML

<div id="wrapper"><span>Mr Frontend</span> does JavaScript</div>

JavaScript

var divElement = document.createElement('div');

var divText = document.createTextNode('Mr Frontend');

divElement.appendChild(divText);

document.querySelector('body').appendChild(divElement);

If you want to see this code working, please check the JS Bin on jsbin.com

Add element to parent div

If you want to add a new element to an already existing element than you have to target that element instead of the body.

Check the example code below!

JavaScript

var divElement = document.createElement('div');

var divText = document.createTextNode('Mr Frontend');

divElement.appendChild(divText);

document.querySelector('#wrapper').appendChild(divElement);

If you want to see this code working, please check the JS Bin on jsbin.com

Remove element

We also want to remove some HTML elements from our page.

It works very simple. Just target a parent element or the body, then use the methodremoveChild to remove your HTML element.

Check the example code below!

HTML

<div id="wrapper"><span class="mrfrontend">Mr Frontend</span> does JavaScript</div>

JavaScript

var paragraph1 = document.querySelector('#p1'); 
var divElement = document.querySelector('#div1'); 

divElement.removeChild(paragraph1);

If you want to see this code working, please check the JS Bin on jsbin.com

Resources W3Schools

Do you need help?

My question for you to answer in the comments, how did you created new elements or removed HTML elements from your page in Vanilla JavaScript? Share it with me! And if you need any help, please let me know 😊


Also published on Medium.

Author Raymon S

Lead Frontend Developer ♥ CSS & Sass / Founder of Mr Frontend Community / Coach & Mentor- #HTML #Sass #BEM #JavaScript #AngularJS #responsive #CoderDojo #NodeJS

More posts by Raymon S
%d bloggers like this: