Selection of multiple html elements with the help of document.getSelection()

47 Views Asked by At

How to iterate through the multiple selected html elements.

const selection = window.getSelection();
const selectedElements = selection.getRangeAt(0).cloneContents().querySelectorAll("*");

This gives all the elements, but I want only selected elements.

1

There are 1 best solutions below

1
Jacob On

querySelectorAll("*") retrieves all elements within the cloned range to filter this down to only the elements you want:

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);
    }
});