I have a selection, like:
const sel = document.getSelection();
that spans one or more HTML elements, or parts of them.
Can’t find a method to get references to those elements.
The closest thing I found was:
sel.anchorNode.cloneNode()
that returns the node’s text, and what I want is a reference to the HTML node in the DOM.
Is it possible? 🙂
>Solution :
To get references to the HTML elements that are part of a selection, you can use the Range object, which provides methods to manipulate the selected content. The Range object can be obtained from the Selection object and provides access to the start and end nodes of the selection, as well as the ability to iterate through the elements within the selection.
Here is a code snippet,
const sel = document.getSelection();
if (sel.rangeCount > 0) {
const range = sel.getRangeAt(0);
let elements = [];
function getElementsInRange(node) {
if (node.nodeType === Node.ELEMENT_NODE) {
elements.push(node);
}
for (let child = node.firstChild; child; child = child.nextSibling) {
if (range.intersectsNode(child)) {
getElementsInRange(child);
}
}
}
getElementsInRange(range.commonAncestorContainer);
console.log(elements);
}
This way, you can get references to all the HTML elements that are part of the selection.