如何迭代多个选定的 html 元素。
const selection = window.getSelection();
const selectedElements = selection.getRangeAt(0).cloneContents().querySelectorAll("*");
这给出了所有元素,但我只想要选定的元素。
querySelectorAll("*")
检索克隆范围内的所有元素,以仅筛选出您想要的元素:
const selection = window.getSelection();
if (!selection.rangeCount) return;
const range = selection.getRangeAt(0);
const clonedSelection = range.cloneContents();
// iterate through all elements
const selectedElements = [];
clonedSelection.querySelectorAll("*").forEach(el => {
// apply your condition here.
// example: check if the element's text is part of the selection
if (range.toString().includes(el.textContent)) {
selectedElements.push(el);
}
});