Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 5.8Creating HTML elements with JavaScript

Being able to add elements to a document after it has loaded can be very useful. By adding elements without updating the whole document HTML, elements which have previously changed will not lose their state.

Creating elements

JavaScript has many methods of creating elements in JavaScript is quite simple and is achieved with the createElement method:

JavaScript
var special_button = document.createElement('button');

This doesn't do anything but create a button element.

The next step is to add the element to the document. This is achieved with the prependChild or appendChild.

JavaScript
var first_preview = document.getElementById('first_preview');
var special_button = document.createElement('button');

first_preview.appendChild(special_button);

Each time the previous code is run it will create a new, empty button. Again, this is pretty useless. The next step will add text using the createTextNode method:

JavaScript
var second_preview = document.getElementById('second_preview');
var special_button = document.createElement('button');

//Add text to the button
special_button.appendChild(document.createTextNode("Test button"));

second_preview.appendChild(special_button);

Of course it is also possible to set attributes on these elements, such as classes or an ID. The following example uses the setAttribute method to set the style attribute on an element:

JavaScript
var third_preview = document.getElementById('third_preview');
var special_button = document.createElement('button');

//Add text to the button
special_button.appendChild(document.createTextNode("Test button"));
//Add the style attribute to the button
special_button.setAttribute('style', "background:#f60;");

third_preview.appendChild(special_button);
Feedback 👍
Comments are sent via email to me.