Thursday, 24. August 2006, 13:14:51
Replacing a page fragment has been an easy task with
outerHTML until one would like to use the
DOM methods for compatibility purpose.
outerHTML (as innerHTML, innerText, outerText) is obviously not part of
DOM and does not work in Firefox (for example).
But here is how to replace any element by anything just by knowing its
id.
This code uses javascript methods available in
DOM level 1. So it should work in every nowadays browsers. I tested it with Opera 9, IE 6 and Firefox 1.5
Here is the fragment we would like to replace :
<dl id="replaceme">
<dt>Umbrella</dt>
<dd>Parapluie</dd>
<dt>Piper</dt>
<dd>Pipo</dd>
</dl>
Here is what we would like to replace it with. In fact, we would like to add a few lines of tags around it. (As an example)
<blockquote style="border-left:thick solid blue" onclick=""alert('coucou')">
<h6 style="text-decoration:underline">Glossaire</h6>
<dl id="replaceme">
<dt>Umbrella</dt>
<dd>Parapluie</dd>
<dt>Piper</dt>
<dd>Pipo</dd>
</dl>
</blockquote>
<p>Youpi bla bla bla</p>
And then here is the javascript code to make the switch. In fact, the last line replaces
old with
new replaceChild(new, old).
Note the
cloneNode(deep) method which is very useful. It duplicates (copies) anything we want. Here we copy it inside our new fragment. If
deep is at
true (our case) it will copy all the childNodes of the element along with the specified element.
The rest of the lines is for building our tags with
DOM methods. It is quite not as easy as with
outerHTML and it is quit difficult to read, but it is standard.
embellish("replaceme");
function embellish(id) {
var source= document.getElementById(id);
/* new page fragment */
var fragment= document.createDocumentFragment();
/* new blockquote */
var block= document.createElement("blockquote");
block.style.borderLeft= "thick solid #333";
block.style.paddingLeft= "4px";
block.onclick= function() { alert("coucou"); };
/* new header */
var titre= document.createElement("h6");
titre.style.textDecoration= "underline";
titre.appendChild(document.createTextNode("Glossaire"));
/* put header in blockquote */
block.appendChild(titre);
/* copy source in blockquote */
block.appendChild(source.cloneNode(true));
/* new paragraph */
var para= document.createElement("p");
para.appendChild(document.createTextNode("Youpi bla bla bla"));
/* put blockquote in page fragment */
fragment.appendChild(block)
/* put paragraph in page fragment */
fragment.appendChild(para);
/* replace source with new fragment (contains a copy of source) */
source.parentNode.replaceChild(fragment, source);
}
To see it in action, see
my french page and click on the big button.