Use execCommand to remove an item so that it is canceled
So I am trying to add a delete button that appears in the hover
elements inside contenteditable
and clicking the delete button removes the element. Right now I have something like this:
button.on("click", function() {
item.remove();
button.hide();
}
However, I would like the deletion to be canceled so that the user can click command+z
on the undo
delete. As far as I know, you will need to use execCommand
to delete an item in order to do this (a custom cancellation solution is not an option). Is there a way to somehow use execCommand
to remove a specific node (even something unselectable, for example iframe
)?
source to share
There is a team delete
. You can set the highlight to include the element in question, invoke the command and it will be canceled, at least in the following simple example, which works in all browsers I've tried:
function deleteElement(id) {
var el = document.getElementById("toBeDeleted");
var range = document.createRange();
range.selectNode(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("delete", false, null);
}
<input type="button" onmousedown="deleteElement('toBeDeleted'); return false" value="Delete">
<div contenteditable="true">Use the button above to delete <b id="toBeDeleted">this bold text</b></div>
source to share