plainJS

Functions / Manipulation

Create a DOM element

jQuery $(string)

2015 page

This is the original page from 2015, kept at its address while the tested rewrite is in progress. The code is of its time: it ran in Internet Explorer and does not use what browsers have gained since. The rewrite replaces it here.

In short

How to create a new element and attach it to the DOM tree.

Use the createElement() method for creating a DOM element:

js
var el = document.createElement('div');

Fill the new element with any HTML content:

js
el.innerHTML = '<p>Hello World!</p>';

Alternatively, use DOM methods for creating content nodes and append them to the new element. This approach requires more code, and is in general slower or equally fast as working with innerHTML:

js
var textnode = document.createTextNode('Hello World!');
el.appendChild(textnode); 

“el” can now be inserted into the DOM tree:

js
document.body.appendChild(el);