matth said:
Anyone know how to iterate over every node in a range? Moz's
documentation seems a little scant on this particular issues, unless
I'm overlooking something.
If you don't care whether the nodes are in place, the quick way is
f = r.cloneContents();
to create a document fragment and proceed from f.firstChild using
nextSibling, visiting childNodes along the way.
If you want to use the nodes in context, then it's something horrible
like this (bookmarklet):
javascript:var nothing={
visited: [],
iterate: function (startNode, endNode) {
var n = startNode;
while (n) {
this.visited.push(n.nodeName);
if (n == endNode) { /* done */
return false;
}
if (n.hasChildNodes()) {
if (!this.iterate(n.firstChild, endNode)) {
return false;
}
}
n = n.nextSibling;
}
n = startNode;
while (!n.nextSibling ) { /* go up to find next content */
n = n.parentNode;
if (n.nodeType == 9){
alert('something badly wrong');
return false;
}
}
this.iterate(n.nextSibling, endNode);
},
go: function(r) {
this.iterate(r.startContainer, r.endContainer);
var a = this.visited.join('\n');
alert('visited ' + this.visited.length + ' nodes between\n' +
a.substring(0, 50) + '...\nand\n...' + a.substring(a.length - 50));
}
}.go(window.getSelection().getRangeAt(0));
This is only a quickie and I suspect it's more recursive than it needs
to be, but the critical bit is that the range may end at a shallower
nesting level than the start; a bit unfamiliar if you're used to working
with well-formed fragments.