Three Ways to Create DOM Elements without jQuery

It seems a lot of people I meet know how to use jQuery to create new DOM elements using code like:

 var myEl = $('<div> ....</div>');
 $('#myDiv').append(myEl);

But I rarely run into people who are aware that you can do this with plain old JavaScript. Honestly, I am not sure why this is true because jQuery is JavaScript. So in this quick post, I will show three different techniques for creating these DOM elements on the fly.

The Element to Create

The first thing we need to do is determine what it is we are going to make. In the examples below I will be creating the following markup:

<div class="container">
    <span class="intro">Hello</span>
    <span id="name"> World!</span>
</div>

We are creating three elements: one div that contains two span elements. I have included attributes of class and id on a couple of the elements so we will need to make sure those get set as well. Now, it's time to write some code.

Using createElement and createTextNode

The first way is to use the built-in document.createElement which takes a string of the tag type and a JavaScript object of properties. Once you have an element, you also need to add the text inside of the element using createTextNode. Finally, we will need to hook them up together and add into the browser DOM. Here is the code using these two methods to create the DOM structure above:

var container = document.createElement('div',{ class: 'container'});
var intro = document.createElement('span',{ class: 'intro'});
var name = document.createElement('span',{ id: 'name'});
var introText = document.createTextNode('Hello');
var nameText = document.createTextNode('World!');

name.appendChild(nameText);
intro.appendChild(introText);
container.appendChild(intro);
container.appendChild(name);

document.body.appendChild(container);

Now, I would typically abstract that out into a single function that can take a parameter that is either a JavaScript object ( that contained all of the DOM information ) or a simple string and have the function return the DOM element(s). But that is fairly brittle code and it's a lot of steps.

Using innerHTML

Next we can use innerHTML method to create the DOM inside of a div element and let the browser do the work for you. So let's create a fake element, set it's innerHTML and return it's children.

var el = document.createElement('div');
var domString = '<div class="container"><span class="intro">Hello</span> <span id="name"> World!</span></div>';
el.innerHTML =  domString;
document.body.appendChild(el.firstChild);    

In this code we created a <div> element, set it's HTML to be all of our DOM elements and then grabbed the first element inside our created <div> (which is our container) and finally, added it to the DOM. Again, this is fairly trivial to create a stand-alone function for doing this whenever you need it.

Using DOMParser

The final way I will show you is to use the DOMParser object which actually creates an entirely new DOM tree that we can get then grab our elements out of. Overall this is similar in technique to the innerHTML above. First, create an instance of the parser then call the parseFromString method. This method takes two parameters: the string to parse and how you want the browser to parse it ( you can use DOMParser to parse other things besides HTML ). Here is the code to create our DOM elements:

var parser = new DOMParser();
var domString = '<div class="container"><span class="intro">Hello</span> <span id="name"> World!</span></div>';
var html = parser.parseFromString(domString, 'text/html');    
document.body.append(html.body.firstChild);

Or, in ES2015+, you could write that as:

const el = ( domstring ) => {
    let html = new DOMParser().parseFromString( domstring , 'text/html');
    return html.body.firstChild;
};
document.getElementById('myID').innerHTML = el('<span>hello world!</span>');

If you want to manipulate the elements before you add them to the DOM, you could have a function that returns all of the DOM nodes as an array:

const parser = ( domstring) => {
    let html = new DOMParser().parseFromString( domstring , 'text/html');
    return Array.from(html.body.childNodes);
};

// since parser returns an array, you can use all of the array methods
// like forEach, filter, sort, reduce, etc
parser( domstring ).forEach(el,i) {
    // your code here
});

Conclusion

You can see that you really don't need jQuery to add elements to the DOM. There are multiple ways to do it readily available to you right out of the gate. Although, I didn't mention browser support, all of these methods should be supported in all modern browsers and IE10 and up. If you need to support older browsers, I would recommend using the innerHTML technique as it probably has the widest support.

'Til next time,
-Gary