DOM: determine if anchorNode or focusNode is on the left side

This method ...

window.getSelection().anchorNode

... tells us where the text STARTS is fetched.

This method ...

window.getSelection().focusNode

... tells us where the ENDS text selection is located.

Since the text can choose to drag left-right or right-left, this does not mean that it anchorNodeis to the left of focusNode.

What DOM / JavaScript method can I use to define a node reference on the LEFT side to select text?

Clarification: this is a bug fix for method startContainer()( window.getSelection().getRangeAt(0).startContainer) and therefore this is an invalid suggestion.

+3
source share
2 answers

Node.compareDocumentPosition() anchorNode focusNode, "left" - DOCUMENT_POSITION_PRECEDING ( RTL-, ). , , , . - :

let selection = window.getSelection();
let position = selection.anchorNode.compareDocumentPosition(selection.focusNode);
if (position & Node.DOCUMENT_POSITION_FOLLOWING)
  alert("Left-to-right selection");
else if (position & Node.DOCUMENT_POSITION_PRECEDING)
  alert("Right-to-left selection");
else
  alert("Only one node selected");
+4

, , , DOM , , :

function isSelectionBackwards() {
    var backwards = false;
    if (window.getSelection) {
        var sel = window.getSelection();
        if (!sel.isCollapsed) {
            var range = document.createRange();
            range.setStart(sel.anchorNode, sel.anchorOffset);
            range.setEnd(sel.focusNode, sel.focusOffset);
            backwards = range.collapsed;
            range.detach();
        }
    }
    return backwards;
}
+2

All Articles