Getting closest node to caret position

I have a document (inside an editable iframe),
I need to find the nearest node to the caret position, not to the parent node, but to the sibling node (so they should have the same parent element) that is (when it is available) left of the carriage position (collapsed selection).

node can be any node, like text node, paragraph, div, etc.
Note. IE is not in the browser .

I have it now:

 var content = document.getElementById('iframedocument').contentWindow;
 var selection = content.getSelection();
 var range = selection.getRangeAt(0); 
+3
source share
2 answers

This works for me:

var content = document.getElementById('iframedocument').contentWindow;
var selection = content.getSelection();
var range = selection.getRangeAt(0); 

var container = range.endContainer;

var lastNodeBeforeCaret = container.lastElementChild;

while (range.comparePoint(lastNodeBeforeCaret, 0) == 1) { 
       lastNodeBeforeCaret = lastNodeBeforeCaret.previousSibling;
}

Another question, firefox adds one or two

<br _moz_dirty=""/>

, , "removechild"?

0

range.startContainer range.endContainer.

https://developer.mozilla.org/en/DOM/range

0

Source: https://habr.com/ru/post/1726586/


All Articles