Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to clone window.getSelection() object?

I'm trying to insert image to editable div. First time is working fine but after user change album (by choose select option) it doesnt work anymore.

The problem is when user 'click' select option it is change (window.getSelection()). I'm solving this problem by trying to clone getSelection object for using when we need it.

So any way to clone window.getSelection() objects?

var sel, range, node;
if (window.getSelection) {
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
        range = window.getSelection().getRangeAt(0);
        node = range.createContextualFragment(image);
        range.insertNode(node);
   }else{

   }
 } else if (document.selection && document.selection.createRange) {
      document.selection.createRange().pasteHTML(image);

 }
like image 279
pors Avatar asked Sep 05 '25 03:09

pors


1 Answers

A Naive cloning would be:

const cloneSelection = (sel = document.getSelection()) => {
    const cloned = {}

    for (const p in sel)
        cloned[p] = sel[p]

    return cloned
}

If you need to clone the range, then do:

const clonedSelection = cloneSelection()
const clonedRange = selection.getRangeAt(0).cloneRange()
clonedSelection.addRange(clonedRange)

But you'll have to access it by selection.getRangeAt(1) since it's been added after the initial one.

like image 104
vsync Avatar answered Sep 07 '25 20:09

vsync