-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathdeleteLastCharacterOutsideSelection.ts
More file actions
40 lines (34 loc) · 1.19 KB
/
Copy pathdeleteLastCharacterOutsideSelection.ts
File metadata and controls
40 lines (34 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
export default function deleteLastCharacterOutsideSelection(html: string) {
const tempInput = document.createElement('div');
tempInput.contentEditable = 'true';
tempInput.style.position = 'absolute';
tempInput.style.left = '-10000px';
tempInput.style.top = '-10000px';
tempInput.innerHTML = html;
tempInput.className = 'allow-selection'; // Patch for Safari
document.body.appendChild(tempInput);
let element = tempInput.lastChild!;
if (element.lastChild) {
// Selects the last and the deepest child of the element.
while (element.lastChild) {
element = element.lastChild;
}
}
const range = document.createRange();
const selection = window.getSelection()!;
if (element.textContent === "") {
range.selectNode(element);
} else {
// Gets length of the element's content.
const textLength = element.textContent!.length;
// Sets selection position to the end of the element.
range.setStart(element, textLength);
range.setEnd(element, textLength);
}
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('delete', false);
const result = tempInput.innerHTML;
document.body.removeChild(tempInput);
return result;
}