Javascript quick reference for newbies : inserting content

Situation : You want to insert some simple content into a DOM element. Since you happen to be a javascript n00b like me who always forget how to do it, and you don't want to use a 60 kb prototype.js for your 10 javascript lines project, you thought it would be useful to write down once for all how this is done. Right ? Hmmkey.

HTML start :

Say the HTML we have is something like the following :

<div>hello <span id="myspan">mister</span> Ozh</div>

Create new content with Javascript :

You will either create a new HTML element (a DIV, a SPAN etc) and its content (innerHTML), or raw text :

var target = document.getElementById('myspan');

// method 1 : create an HTML element
var content = document.createElement('span');
content.innerHTML = 'I am an <em>inserted</em> SPAN';

// method 2 : create raw text with no markup
var newtext = document.createTextNode('INSERTED');

Insert Before :

target.parentNode.insertBefore(content, target);

HTML result :

hello INSERTED<span id="myspan">mister</span> Ozh

Insert at the Top :

target.insertBefore(content, target.firstChild);

HTML result :

hello <span id="myspan">INSERTEDmister</span> Ozh

Insert at the Bottom :

target.appendChild(content);

HTML result :

hello <span id="myspan">misterINSERTED</span> Ozh

Insert After :

target.parentNode.insertBefore(content, target.nextSibling);

HTML result :

hello <span id="myspan">mister</span>INSERTED Ozh

prototype functions

For reference, using javascript framework prototype, these 4 content insertion can be achieved with the following :

new Insertion.Before(target, content);
new Insertion.Top(target, content);
new Insertion.Bottom(target, content);
new Insertion.After(target, content);

2 comments

  1. Frank

    First Post!

    thanks for that – /me iz teh javascript n00b.

  2. Dx

    thiz post rlz

Comments are closed.