The dom manipulation concept within the Angular (not AngularJS) got complicated compared with the common approach we got used to with Javascript and JQuery. Such complexity is inevitable for security and usability. In this article I propose a concept approaching text highlighting.
window.getSelection()
Returns a Selection
object representing the range of text selected by the user or the current position of the caret. The selection range may include several nodes:
window.getSelection().focusNode.childNodes
As the first and the last nodes may be partially selected, The Selection
object range supply the range.startContainer
and range.endContainer
.
Range Corner Cases
Highlighting In same element: The containers will be equal.
Highlighting In different elements: start container or end container are partially selected: In this case you need to compare the element’s data
length with the offsets of the containers. The next code demonstrates how it is devided:
let range = sel.getRangeAt(0) let left_str, right_str; left_str = range.startContainer.data.substring(0, range.startOffset); right_str = range.endContainer.data.substring(range.endOffset);
The next figure illustrate the ranges:
In this snippet, the left_str
will be “example ” and the right_str
will be ” is bold”.
Anchor and Focus
In document selection, the selection direction may start whether from left or right. The Selection object API has the anchor and the focus. The anchor is where the user began the selection and the focus is where the user ends the selection. If you make a selection with a desktop mouse, the anchor is placed where you pressed the mouse button and the focus is placed where you released the mouse button. Anchor and focus should not be confused with the start and end positions of a selection, since anchor can be placed before the focus or vice versa, depending on the direction you made your selection.
The base and extent comes to ignore the selection.