Search code examples
javascriptjquerygetselection

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.


Solution

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