Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get references to DOM elements of a selection

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? 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading