faqts : Computers : Programming : Languages : JavaScript : DHTML

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

77 of 98 people (79%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

How to replace an element's content with DOM methods?

Feb 7th, 2000 04:12
Martin Honnen,


DOM level 1 provides no methods like IE's innerHTML to replace the 
content of an element with a html source string to parse. You are 
supposed to manipulate the DOM tree by creating new HTML elements and 
deleting old ones/ replacing them. 
HTML elements (tagged elements) are created with the
  var el = document.createElement('TAGNAME')
method call, text nodes are created with
  var textNode = document.createTextNode('text content');
To remove all the children of a html (or xml) element you get a 
reference to the element e.g.
  var el = document.getElementById('elementId');
and the remove all children with
  while (el.hasChildNodes())
    el.removeChild(el.lastChild);
To insert a child node into an element you call
  el.appendChild(node)
for example 

<SCRIPT>
function insertNewDate(el) {
  while (el.hasChildNodes())
    el.removeChild(el.lastChild);
  var textNode = document.createTextNode(new Date());
  el.appendChild(textNode);
}
</SCRIPT>


<SPAN ID="aSpan" STYLE="cursor: hand;" ONCLICK="insertNewDate(this)">
<SCRIPT>
document.write(new Date())
</SCRIPT>
</SPAN>