How to select HTML elements with document.getSelection() in JavaScript,

24 Views Asked by At

let selection =document.getSelection(); let cloned = selection.getRangeAt(0); for(let i =0; i <selection.rangeCount; i++) { cloned.append(selection.getRangeAt(i).cloneContents());}

Whenever, I tried to select multiple Html elements, it gives me whole body as selection.

    const handleFormatBlock = (action: any): any => {
        const iframeDoc = _editorRef.current.contentWindow.document;
        const selection = iframeDoc.getSelection();
        if (!(selection && selection.rangeCount > 0)) {
            return;
        }
        const range = selection.getRangeAt(0);
        const fragment = document.createDocumentFragment();
        let returnFragment;
        console.log(range);
        // For multiple selection
        if (range.commonAncestorContainer.childNodes.length > 1) {
            console.log('multiple selection');
            const nodes = Array.from(range.commonAncestorContainer.children);
            const cloneNodes = Array.from(range.cloneContents().children);
            const selectedNodes = nodes.filter((node: any) => cloneNodes.some((cloneNode: any) => node.textContent === cloneNode.textContent));
            console.log(selectedNodes, 'selected nodes');
            selectedNodes.forEach((node: any) => {
                console.log(node);
            });
            range.deleteContents();
            range.insertNode(returnFragment)
        }
0

There are 0 best solutions below