Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getSelection not working on image

I want to get the selected content inside iframe design mode. I am using following code.

function getIframeSelectionText(iframe) {
    var win = iframe.contentWindow;
    var doc = iframe.contentDocument || win.document;

    if (win.getSelection) {

        return win.getSelection();
    } else if (doc.selection && doc.selection.createRange) {
        return doc.selection.createRange().text;
    }
}

i am able to get the text for i cannot get the image that is also selected. Please help.

like image 232
Jagrit Ojha Avatar asked Sep 03 '25 06:09

Jagrit Ojha


1 Answers

You can use Range Object to achieve that:

function getImg(iframe) {
  var win = iframe.contentWindow;
  var doc = iframe.contentDocument || win.document;

  // get Range object
  var range = win.getSelection().getRangeAt(0)

  // now you get a copy of the nodes that been selected
  var fragment = range.cloneContents()

  // now you can do whatever you want with fragment,
  // such as find img element
  var imgs = fragment.querySelectorAll('img')

}
like image 112
L_K Avatar answered Sep 04 '25 18:09

L_K