Lukasz Indyk wrote:
i have a piece of html code, and want to replace every image on my page
with this code. now i do it by replacing IMG node with SPAN node, and
then setting innerHTML property of SPAN node with my html code:
var nodeToReplaceWith = document.createElement("<SPAN>");
nodeToReplaceWith.innerHTML = HTMLCodeToReplaceWith;
node.replaceNode(nodeToReplaceWith);
but when i use this approach i have a problem, because when in my html
code there is ampersand (&), then it is escaped with &
it is strange for me, because other special characters (<,>) are not
escaped.
so, my question is: how to replace IMG node without using "SPAN
approach" described above, and how to avoid escaping ampersand (if
someone knows why only ampersand is escaped, i would be very happy to
hear his explanation).
The W3C DOM in level 1 and 2 doesn't provide any API to replace a node
with a snippet of markup to be parsed. Thus you depend on browser
extensions to do that, IE4+ and Opera 7 provide
element.outerHTML = '...your HTML snippet here'
however for Mozilla and Netscape that doesn't work, your span
replacement is not that bad an approach, alternatively you could use
range extension function createContextualFragment e.g.
function setOuterHTML (element, html) {
if (typeof element.outerHTML != 'undefined') {
element.outerHTML = html;
}
else {
var range;
if (document.createRange && (range = document.createRange())
&& range.createContextualFragment) {
range.selectNode(element);
var docFrag = range.createContextualFragment(html);
element.parentNode.replaceChild(docFrag, element);
}
}
}
for (var i = 0; i < document.images.length; i++) {
setOuterHTML(document.images[i], '<p>Kibology for all. ' + i + '<\/p>');
}
That way you use outerHTML for IE, Opera (and I think Konqueror) and for
Mozilla/Netscape a document fragment is created from the HTML snippet
--
Martin Honnen
http://JavaScript.FAQTs.com/