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?

30 of 35 people (86%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How do I append some HTML to a loaded page?

Sep 22nd, 2001 04:10
Martin Honnen,


With IE4+ you can use 
  element.insertAdjacentHTML('beforeEnd', 'html here')
to insert some html before the end tag of the element. When you want to 
add to the complete page the document.body element is the right one to 
choose.
With NN6 you need to create a range and use its createContextualFragment 
method to parse the html into a document fragment which you can then 
append to the document.body element.
NN4 can't really insert new content into the page, all it can do is 
create layers and position them at the end of the page.
Here is an example function addHTML which implements the code for IE4+, 
NN4, and NN6/Mozilla.
The example page allows you to add the current date at the end of the 
page.
<html>
<head>
<title>
page content addition
</title>
<script type="text/javascript">
function addHTML (html) {
  if (document.all)
    document.body.insertAdjacentHTML('beforeEnd', html);
  else if (document.createRange) {
    var range = document.createRange();
    range.setStartAfter(document.body.lastChild);
    var docFrag = range.createContextualFragment(html);
    document.body.appendChild(docFrag);
  }
  else if (document.layers) {
    var l = new Layer(window.innerWidth);
    l.document.open();
    l.document.write(html);
    l.document.close();
    l.top = document.height;
    document.height += l.document.height;
    l.visibility = 'show';
  }
}
</script>
</head>
<body>
<form name="formName">
<input type="button"
       onclick="addHTML('<b>' + new Date() + '<\/b><br \/>');"
       value="add current date"
/>
</form>
</body>
</html>