I am trying to write a function that will, on keyup
, give me a reference to the element immediately preceding the caret in a contentEditable div.
If the caret is in a text node then the function should return null
. If the caret is at the start of the contentEditable then the function should return null
.
But if the caret is at the start of a text node, and this text node is immediately preceded by an element such as a Span, then the function should return a reference to this element.
And, if the caret is placed between two Html elements (e.g. between two Spans), then it should return a reference to the element which immediately precedes the caret, i.e the first of the two elements.
If there are two or more text nodes which immediately follow one another, then they should be considered as a single text node.
I've started to cobble something together. I'm considering using range offsets to work out how far into a text node I am, but it feels overly complicated. I can't help thinking there's something obvious I'm not thinking of.