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?

57 of 65 people (88%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

What is the Netscape equivalent of element.insertAdjacentHTML()?

Aug 25th, 2000 09:12
Martin Honnen, James van der Spuy,


NN4 doesn't have comparable methods as it cannot insert into an already 
loaded document and reflow the content dynamically.
NN6 can however do that though it has different methods than IE's 
insertAdjacentHTML. There are two ways: 
1) Use DOM methods to create HTML elements and to insert them into the 
document tree. Example:
   var img = document.createElement('IMG');
   img.src = 'kiboInside.gif';
   img.name = 'imageName';
creates and intializes an HTMLImageElement. This can now be inserted 
where you like for instance
   document.body.appendChild(img);
inserts at the end of the BODY. To insert at the beginning of the BODY 
use
   document.body.insertBefore(img, document.body.firstChild)
To insert at the beginning or end of another element use
   document.getElementById('elementId').insertBefore(
     img, document.getElementById('elementID').firstChild);
respectively
   document.getElementById('elementID').appendChild(img);
These DOM methods above work not only with NN6 but also with IE5 while 
IE4 doesn't support them.
The disadvantage of these methods is that you can't parse a string of 
html into the document (as with insertAdjacentHTML) but need to 
construct the elements yourself.
2) NN6 provides a Range object which has a 
  createContextualFragment
method to parse HTML into a document fragment which can then be 
inserted into the document tree with DOM methods; for instance
   var range = document.createRange();
   range.setStartBefore(document.body.lastChild);
   var docFrag = 
     range.createContextualFragment('<IMG SRC="kiboInside.gif">');
   document.body.appendChild(docFrag)
inserts the IMG HTML at the end of the body (comparable to 
insertAdjacentHTML('beforeEnd', ...)).
To insert at the beginning use
  var range = document.createRange();
  range.setStartBefore(document.body.firstChild);
  var docFrag = 
    range.createContextualFragment('<IMG SRC="kiboInside.gif">');
  document.body.insertBefore(docFrag, document.body.firstChild);
For an element other than the BODY replace document.body with 
document.getElementById('elementId')