How to get the image element after insert using execCommand?

Najib Razak picture Najib Razak · Sep 20, 2012 · Viewed 13.8k times · Source

Is there any way to get the image element after we insert the image using execCommand? for example

e.execCommand('insertimage',0,'ronaldo.png')

Answer

Kernel James picture Kernel James · Jul 3, 2013

Don't use insertimage, use plain old insertHTML and give the element you are inserting an ID so that you can reference it later. i.e.,

function insertHTML(img) {
  var id = "rand" + Math.random();
  var doc = document.getElementById("editor");
  doc = doc.document ? doc.document : doc.contentWindow.document;
  img = "<img src='" + img + "' id=" + id + ">";

  if(document.all) {
    var range = doc.selection.createRange();
    range.pasteHTML(img);
    range.collapse(false);
    range.select();
  } else {
    doc.execCommand("insertHTML", false, img);
  }
  return doc.getElementById(id);
};