Changing HTML Fragments


list.innerHTML += newNode; 

Changing text nodes (either by replacing them or by using the nodeValue property) changes only actual text, but you cannot change complete HTML fragments, including subelements. To do that, the innerHTML property of every element may prove useful. Although innerHTML is not standardized and is not part of any DOM specification, it works just fine. With innerHTML, you can change the inner HTML of any HTML element and even provide new subelements, as the following listing shows:

Adding Elements via innerHTML (innerhtml.html)

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

So instead of using the clean and inconvenient DOM approach, innerHTML just writes the HTML into one element. Both approaches have their individual advantages and disadvantages: innerHTML requires that you take care of character encoding by yourself, but on the other hand it allows you to add or change several elements at once.




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