"Phil" <pa*******@pasd email.com> writes:
Thanks for your example, but I can already made this. What I want is really
displaying (document.write ) the tree, with nodes, children and so forth
(Missing closing tags is not the point, I write this on the fly and I know
they are missing)
I'll just write it as a string here, I'm sure you can convert the output
to your needs.
I can see two methods. One uses the document.getEle mentsByTagName( "div")
collection and finds the structure by checking which elements are inside
each other. The other uses recursive descent on the tree. In both cases,
I build a datastructure of nodes on the form
node ::= {elem: DivNode, children: [array of divs nested inside DivNode]}
Using div collection, assuming that the divs are in the order the
start tags occour in the document (as I believe they should be):
---
// function that checks whether node2 is a predecessor of node1
function parentOf(node1, node2) {
while(node1!=nu ll) {
if (node1 == node2) {return true;}
node1 = node1.parentNod e;
}
return false;
}
function findDivsNest(el em) {
var divs = elem.getElement sByTagName("div ");
var stack = [];
var topNode = {elem:elem,chil dren:[]};
var currentNode = topNode;
for (var i = 0; i<divs.length;i ++) {
var div = divs[i];
while (!parentOf(div, currentNode.ele m)) {
currentNode = stack.pop();
}
var thisNode = {elem:div,child ren:[]};
currentNode.chi ldren.push(this Node);
stack.push(curr entNode);
currentNode = thisNode;
}
return topNode.childre n;
}
---
Recursive descent version:
---
function findDivsRec(nod e) {
if (node.nodeType != 1 && node.nodeType != 9) {
return []; // non-element, non-document node
}
var divs = [];
for (var chld = node.firstChild ; chld != null; chld=chld.nextS ibling) {
divs = divs.concat(fin dDivsRec(chld)) ;
}
if (/^div$/i.test(node.tag Name)) {
return [{elem:node,chil dren:divs}];
} else {
return divs;
}
}
---
An example of how to output the data as text:
---
function divsToLines(div s,indent) {
indent = indent || "";
var nextIndent;
var result = [];
for (var i=0;i<divs.leng th;i++) {
var div=divs[i];
if (div.children.l ength > 0) {
nextIndent = nextIndent || indent + " "; // calc once
result.push(ind ent+" + <div id=\""+div.elem .id+"\">");
result = result.concat(d ivsToLines(div. children,nextIn dent));
result.push(ind ent+" <\/div>");
} else {
result.push(ind ent+" - <div id=\""+div.elem .id+"\"><\/div>");
}
}
return result;
}
function divsToString(di vs) {
return divsToLines(div s).join("\n");
}
---
You can then test it with
alert(divsToStr ing(findDivsRec (document)));
or
alert(divsToStr ing(findDivsNes t(document)));
If you want the output to be HTML, it's easy to fix.
/L
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'