indiWiz.com

Subhash's Tech Log

JavaScript: Dynamically Creating and Manipulating DOM Elements

without comments

I was pleasantly surprised to see that JavaScript now supports XML-DOM methods for manipulating JavaScript DOM trees. A quick look at the features:

Init

Before we proceed with the examples, the setup part. All the examples that follow assume the existence of this in the HTML page:

<div id="placeholderId"/>

Creating new element

Let us assume the requirement of placing <br/> element inside the placeholder. The code:

var e = document.getElementById('placeholderId');
var eBr = document.createElement('br');
e.appendChild(eBr);

Adding attribute

Suppose we want to add the attribute id="brId", we would write:

eBr.setAttribute('id', 'brId');

Deleting attribute

eBr.removeAttribute('id');

Deleting element

var e = document.getElementById('brId');
var eParent = e.parentNode;
eParent.removeChild(e);

Creating elements with text element

Consider that we want to have the following paragraph element inside the placeholderId <div>:

<p align="right">Hello World!</p>

It can be achieved thus:

var e = document.getElementById('placeholderId');
var ePara = document.createElement('p');
ePara.setAttribute('align', 'right');
var eTxt = document.createTextNode('Hello World!');
ePara.appendChild(eTxt);
e.appendChild(ePara);

Happy hacking with this info ;-)

Written by Subhash Chandran

December 10th, 2008 at 9:24 am

Posted in Scripting

Tagged with

Leave a Reply