I'm using rangy in my project. I want to test if an element is fully selected. I tried the following:
selRange.containsNode( el );
Note: selRange is simply a reference to window.getSelection().getRangeAt(0);
When the selection was made from top to the bottom, it works but not the other way around.
Safari and Chrome return different results depending if you made a bottom up or top down selection. Any ideas?
Exactly what is considered selected depends on how the selection was made and which browser you're using. If you're just interested in whether all of the text within an element is selected, Rangy's Range
object provides a non-standard convenience method for this:
selRange.containsNodeText(el);
Here is a non-Rangy equivalent. It isn't fully tested but I think it will work.
function containsNodeText(range, node) {
var treeWalker = document.createTreeWalker(node,
NodeFilter.SHOW_TEXT,
{ acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
false
);
var firstTextNode, lastTextNode, textNode;
while ( (textNode = treeWalker.nextNode()) ) {
if (!firstTextNode) {
firstTextNode = textNode;
}
lastTextNode = textNode;
}
var nodeRange = range.cloneRange();
if (firstTextNode) {
nodeRange.setStart(firstTextNode, 0);
nodeRange.setEnd(lastTextNode, lastTextNode.length);
} else {
nodeRange.selectNodeContents(node);
}
return range.compareBoundaryPoints(Range.START_TO_START, nodeRange) < 1 &&
range.compareBoundaryPoints(Range.END_TO_END, nodeRange) > -1;
}