Anh Tú
Anh Tú

Reputation: 636

javascript execCommand('delete') not delete all selection div in chrome

I try to write an editor with contenteditable & execCommand Everything works fine on Firefox, but in chrome has an error with 'delete' command.

Please view bellow photo:

enter image description here

This is my code:

var $obj = $('#myBlockDivId');
var selection = rangy.getSelection();
if (selection.rangeCount > 0) selection.removeAllRanges();
var range = rangy.createRange();
range.selectNode($obj[0]);
selection.addRange(range);
range.select();

when i console log: rangy.getSelection().toHtml() ==> it's right

but when i call:

document.execCommand("delete", null, false);

it's fine on Firefox but not right on Chrome, the wrapper div is not being deleted.

How can i fix this? I have to use execCommand because it's support undo and redo function. so, i can't use jquery or javascript dom selector to remove div.

(I bad at English, someone please edit my question for more clearly, many thanks)

Upvotes: 5

Views: 5820

Answers (2)

Manish Kumar
Manish Kumar

Reputation: 395

Try :

document.execCommand("delete", false, null);

Instead of :

document.execCommand("delete", null, false);

Upvotes: 2

Anonymous0day
Anonymous0day

Reputation: 3042

Maybe you can try to do :
(note the argument alone)

<span contentEditable>
	Select something here and after click on delete.
</span>
<input type="button" value="Delete selection" onclick="document.execCommand('delete')"/>


Acording to w3c.github.io on Enabled commands :

At any given time, a supported command can be either enabled or not. Authors can tell whether a command is currently enabled using queryCommandEnabled(). Commands that are not enabled do nothing, as described in the definitions of the various methods that invoke commands.

Some helpfull links :

w3c Unofficial Draft 15 October 2015:

Other ressources :

Hope this will help you !

Upvotes: 3

Related Questions