0

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
  • this question is not very clear at all. what does it even mean, to you, to assign a javascript value to a html element? Commented Feb 5, 2010 at 7:44

2 Answers 2

2

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';
Sign up to request clarification or add additional context in comments.

2 Comments

DOM 1 came out in 1998. I don't think it qualifies as 'new' any longer :)
Try telling that to the innerHTML crowd.
0
var el = document.createElement('div');
el.innerHTML = '3';
document.body.appendChild(el);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.