Albert Wagner <al******@tcac.net> writes:
On 07 Oct 2003 15:29:43 +0200
Lasse Reichstein Nielsen <lr*@hotpop.com> wrote:
<snip> javascript:document.body.innerHTML.replace(/&/g,"&").replace(/</
g,"<")
<snip>
How would you do this without using .innerHTML?
Much harder :)
I would traverse the DOM document tree and build the corresponding
HTML:
function traverse(node){
if (node.nodeType == 3){
return node.nodeValue.replace(/&/g,"&").replace(/</g,"<"));
}
if (node.nodeType == 1){
var tag="<"+node.tagName;
var attr = node.attributes;
for (var i=0;i<attr.length;i++) {
tag+=" "+attr[i].name+"=\""+attr[i].value+"\"";
}
tag += ">";
for (var chld=node.firstChild;chld;chld=chld.nextSibling) {
tag+=traverse(chld);
}
tag+="<\/"+node.tagName+">";
return tag;
}
return "";
}
You can then use
traverse(document.body).replace(/&/g,"&").
replace(/</g,"<").
replace(/\n/g,"<br>")
to get an HTML representation of the document structure.
To create it as a bookmarklet, you have to includ the function in the
bookmark. That takes some munging to get on one line:
javascript
: function traverse(node){ if (node.nodeType == 3){ return node.nodeValue.replace(/&/g,"&").replace(/</g,"<"); } if (node.nodeType == 1){ var tag="<"+node.tagName; var attr = node.attributes;for (var i=0;i<attr.length;i++) { tag+=" "+attr[i].name+"=\""+attr[i].value+"\""; } tag += ">"; for (var chld=node.firstChild;chld;chld=chld.nextSibling) { tag+=traverse(chld); } tag+="<\/"+node.tagName+">"; return tag; } return ""; }traverse(document.body).replace(/&/g,"&").replace(/</g,"<").replace(/\n/g,"<br>")
This simple code makes end tags for all tags, including </img> and </input>.
It might be too long for some browsers. It works in Opera 7.2, but not
in Mozilla FB and IE. Since they both have innerHTML, it's not that
important. It will never work in Netscape 4, no matter what method is used.
/L
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'