问题
在网页上选中文本,然后获取选中文本的所有 DOM 块元素。
解决
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);
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;
}