Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  12] [ 6]  / answers: 1 / hits: 22121  / 15 Years ago, fri, march 20, 2009, 12:00:00

I'm trying to get all the DOM nodes that are within a range object, what's the best way to do this?



var selection = window.getSelection(); //what the user has selected
var range = selection.getRangeAt(0); //the first range of the selection
var startNode = range.startContainer;
var endNode = range.endContainer;
var allNodes = /*insert magic*/;


I've been been thinking of a way for the last few hours and came up with this:



var getNextNode = function(node, skipChildren){
//if there are child nodes and we didn't come from a child node
if (node.firstChild && !skipChildren) {
return node.firstChild;
}
if (!node.parentNode){
return null;
}
return node.nextSibling
|| getNextNode(node.parentNode, true);
};

var getNodesInRange = function(range){
var startNode = range.startContainer.childNodes[range.startOffset]
|| range.startContainer;//it's a text node
var endNode = range.endContainer.childNodes[range.endOffset]
|| range.endContainer;

if (startNode == endNode && startNode.childNodes.length === 0) {
return [startNode];
};

var nodes = [];
do {
nodes.push(startNode);
}
while ((startNode = getNextNode(startNode))
&& (startNode != endNode));
return nodes;
};


However when the end node is the parent of the start node it returns everything on the page. I'm sure I'm overlooking something obvious? Or maybe going about it in totally the wrong way.



MDC/DOM/range


More From » dom

 Answers
23

The getNextNode will skip your desired endNode recursively if its a parent node.



Perform the conditional break check inside of the getNextNode instead:



var getNextNode = function(node, skipChildren, endNode){
//if there are child nodes and we didn't come from a child node
if (endNode == node) {
return null;
}
if (node.firstChild && !skipChildren) {
return node.firstChild;
}
if (!node.parentNode){
return null;
}
return node.nextSibling
|| getNextNode(node.parentNode, true, endNode);
};


and in while statement:



while (startNode = getNextNode(startNode, false , endNode));

[#99813] Monday, March 16, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yosefleod

Total Points: 113
Total Questions: 100
Total Answers: 115

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago
;