Creating Text Elements


var newTextNode =   document.createTextNode("Item " + nr); 

If you want to put text within an element, you need a text node that is a subnode of the actual element node. The createTextNode() method creates such a text node; you just provide the actual text.

In the following code, once again list elements are added; however, this time they do get text inside them. So first you create a text node, and then you append this text node to another node (which then could be appended to another node, which could be appended to yet another node, which…you get the picture).

Creating (and Adding) a Text Node (textnode.html)

<script language="JavaScript"   type="text/javascript"> var nr = 1; function addItem() {   var list = document.getElementById("list");   var newNode = document.createElement("li");   nr++;   var newTextNode =     document.createTextNode("Item " + nr);   newNode.appendChild(newTextNode);   list.appendChild(newNode); } </script> <ul ><li>Item 1</li></ul> <input type="button" onclick="addItem();"   value="Add item" /> 




JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net