In: , ,
On: 2006 / 06 / 14
Shorter URL for this post: http://ozh.in/dd

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);

Shorter URL

Want to share or tweet this post? Please use this short URL: http://ozh.in/dd

Metastuff

This entry "Javascript quick reference for newbies : inserting content" was posted on 14/06/2006 at 7:45 pm and is tagged with , ,
Watch this discussion : Comments RSS 2.0.

2 Blablas

  1. Frank says:

    First Post!

    thanks for that – /me iz teh javascript n00b.

  2. Dx says:

    thiz post rlz

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar and sign for a free account
Spam: Various spam plugins may be activated. I'll put pins in a Voodoo doll if you spam me.

Read more ?