JSFiddle - React, Tailwind, and code Playground
HTML
<input type="button" id="insertButton" value="Insert image" unselectable="on">
<div contenteditable="true" id="editor">Place the caret in here somewhere and press the button to insert an image.</div>
JavaScript
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.getElementById("insertButton").onmousedown = function() {
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);
}
}
};