0%

JS 获取选中文本的所有 DOM 块元素

问题

在网页上选中文本,然后获取选中文本的所有 DOM 块元素。

解决

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var allWithinRangeParent = range.commonAncestorContainer.getElementsByTagName("*");

var allSelected = [];
for (var i=0, el; el = allWithinRangeParent[i]; i++) {
// The second parameter says to include the element
// even if it's not fully selected
if (selection.containsNode(el, true) ) {
allSelected.push(el);
}
}

console.log('All selected =', allSelected);
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
function getSelectedBlockElements() {
const selection = window.getSelection();
if (selection.rangeCount === 0) return [];
const range = selection.getRangeAt(0);
const startContainer = range.startContainer;
const endContainer = range.endContainer;
const startElement = startContainer.nodeType === 3 ? startContainer.parentElement : startContainer;
const endElement = endContainer.nodeType === 3 ? endContainer.parentElement : endContainer;
const commonAncestor = range.commonAncestorContainer;
const commonAncestorElement = commonAncestor.nodeType === 3 ? commonAncestor.parentElement : commonAncestor;
const startElementParents = [startElement];
let startElementParent = startElement.parentElement;
while (startElementParent !== commonAncestorElement) {
startElementParents.push(startElementParent);
startElementParent = startElementParent.parentElement;
}
const endElementParents = [endElement];
let endElementParent = endElement.parentElement;
while (endElementParent !== commonAncestorElement) {
endElementParents.push(endElementParent);
endElementParent = endElementParent.parentElement;
}
const blockElements = [];
let startElementParentsIndex = 0;
let endElementParentsIndex = 0;
let startElementParentElement = startElementParents[startElementParentsIndex];
let endElementParentElement = endElementParents[endElementParentsIndex];
while (startElementParentElement !== endElementParentElement) {
blockElements.push(startElementParentElement);
startElementParentsIndex++;
startElementParentElement = startElementParents[startElementParentsIndex];
}
blockElements.push(startElementParentElement);
return blockElements;
}

后记