views:

38

answers:

2

all,

How to create an element in javascript, say <div></div> and i want to assign a javascript value to it say var a=3;

Example:

<script>
var ele=create element('<div>');
ele.add(a)
</div>
</script>

Thanks..........

+1  A: 

The new, W3C approved way is to use document.createElement for creation and Node.appendChild or Node.insertBefore to add the new node as a child of another. These functions are defined by the DOM level 1 standard.

To add text to a node, create it with document.createTextNode, then add the text node using one of the previously mentioned methods. To change the text in a text node, assign to the text node's nodeValue property.

// create the element
var elt = document.createElement('div');
// create & add text to the element
elt.appendChild(document.createTextNode('foo'));
// add the element to the body as the middle child
document.body.insertBefore(elt, document.body.childNodes[document.body.childNodes.length >> 1]);
...
// change the text stored in the element
elt.firstChild.nodeValue='bar';
outis
DOM 1 came out in 1998. I don't think it qualifies as 'new' any longer :)
David Dorward
Try telling that to the `innerHTML` crowd.
outis
Amazing explanation...............Thanks
Hulk
A: 
var el = document.createElement('div');
el.innerHTML = '3';
document.body.appendChild(el);
Jimmy Cuadra
Thanks...............In short i needed this..........
Hulk