How to get image element after insert using execCommand?

Is there a way to get an image element after inserting an image using execCommand? eg

e.execCommand('insertimage',0,'ronaldo.png') 
+7
source share
3 answers

Do not use insertimage , use the plain old insertHTML and specify the element into which you insert the identifier in order to refer to 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); }; 
+11
source

You can use the fact that browsers place the carriage immediately after the inserted image and work from there. This requires DOM Range and selection support, which excludes IE <= 8, but if it is important, you can use a library like my Rangy to fill this gap.

Demo: http://jsfiddle.net/xJkuj/

the code:

 function previousNode(node) { var previous = node.previousSibling; if (previous) { node = previous; while (node.hasChildNodes()) { node = node.lastChild; } return node; } var parent = node.parentNode; if (parent && parent.nodeType.hasChildNodes()) { return parent; } return null; } document.execCommand("InsertImage", false, "http://placekitten.com/200/300"); // Get the current selection var sel = window.getSelection(); if (sel.rangeCount > 0) { var range = sel.getRangeAt(0); var node = range.startContainer; if (node.hasChildNodes() && range.startOffset > 0) { node = node.childNodes[range.startOffset - 1]; } // Walk backwards through the DOM until we find an image while (node) { if (node.nodeType == 1 && node.tagName.toLowerCase() == "img") { alert("Found inserted image with src " + node.src); break; } node = previousNode(node); } } 
+5
source

This is my way:

 e.execCommand('insertimage', 0, URI) // image URI image=$('img[src="'+URI+'"]').not('.handled').addClass('.handled'); //.not('.handled').addClass('.handled') is needed if there are many images with the same URI 
+2
source

All Articles