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 :

  1. <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 :

  1. var target = document.getElementById('myspan');
  2.  
  3. // method 1 : create an HTML element
  4. var content = document.createElement('span');
  5. content.innerHTML = 'I am an <em>inserted</em> SPAN';
  6.  
  7. // method 2 : create raw text with no markup
  8. var newtext = document.createTextNode('INSERTED');

Insert Before :

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

HTML result :

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

Insert at the Top :

  1. target.insertBefore(content, target.firstChild);

HTML result :

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

Insert at the Bottom :

  1. target.appendChild(content);

HTML result :

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

Insert After :

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

HTML result :

  1. 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 :

  1. new Insertion.Before(target, content);
  2. new Insertion.Top(target, content);
  3. new Insertion.Bottom(target, content);
  4. 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.