JavaScript: Hello DOM

Just real quick, this came up in #javascript the other day. Working with the DOM, appending new elements.

Here’s the basic idea.

You have your DOM, and with JavaScript, there are ways to manipulate nodes. Including adding new ones. When you want to add new elements to your DOM, you have to think about this in a few different steps.

First step, where am I placing this?

The reason for this is because you have to select an element to append your new element to. You can append it to the body, the head, or other element. So we start this off with the assumption that we have a div with the id of inner_content.

So we start out our JavaScript with:

1
var main_div = document.getElementById('inner_content');

Second step, what are we going to create?

Let’s say we want to add another div with some text inside of it. So, we now create the new div, and append it to our main_div variable.

1
var new_div = document.createElement('div');

This div needs some attributes! So let’s hop into that, the above snippet turns into:

1
2
3
4
var new_div = document.createElement('div');
new_div.setAttribute('id','sub_div');
new_div.setAttribute('class','mySubDivCssClass');
new_div.setAttribute('onclick','javaScriptFunction()');

Third, attach

Now we need to actually attach this item to our old div.

To do that we simply tell our main_div to append a child:

1
main_div.appendChild( new_div );

Now, say we want to add a text node… now that gets its own special tool.

1
var new_text = document.createTextNode('My New Text');

And now, just like before, we need to attach that to an item it belongs to.

1
new_div.appendChild( new_text );

Finally

Now, we end up with our code snippet looking something like this:

1
2
3
4
5
6
7
8
9
10
11
12
var main_div = document.getElementById('inner_content');
var new_div = document.createElement('div');
var new_text = document.createTextNode('My New Text');
// now set up our attributes
new_div.setAttribute('id','sub_div');
new_div.setAttribute('class','mySubDivCssClass');
new_div.setAttribute('onclick','javaScriptFunction()');
// now append the text to the new div
new_div.appendChild( new_text );
// now append our new div to our main div
main_div.appendChild( new_div );
// done.

And that’s about as easy as it gets.

Hope this helps someone understand the order that is required when appending new children to the node list.

For more information:

http://www.w3schools.com/htmldom/
http://www.w3.org/TR/DOM-Level-2-HTML/
http://developer.mozilla.org/en/docs/Using_the_W3C_DOM_Level_1_Core