Jagrit Ojha
Jagrit Ojha

Reputation: 177

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.

Upvotes: 4

Views: 1788

Answers (1)

L_K
L_K

Reputation: 2986

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')

}

Upvotes: 6

Related Questions