Search code examples
javascriptrangeexeccommand

Custom execCommand command


I'm trying to find a way to have a custom command with document.execCommand. Basically, I need to have something similar to

document.execCommand('customCommand');

customCommand in this case would wrap selected content with specific tags. I was able to achieve that by using range.surroundContents, but, what I also need is to be able to undo the operation at any given time. So for example, when you do execCommand('bold') twice, after the first run it makes the text bold and the second run unbolds it.

Is there something like range.unsurroundContents ?


Solution

  • You may want to read the Mozilla example of Rich-Text editing:

    https://developer.mozilla.org/en-US/docs/Rich-Text_Editing_in_Mozilla

    I do not think you can use the execCommand() to do those things. Plus, execCommand() is not very cross browser friendly.

    The best is probably to write your own functions that manipulates the DOM. They have examples doing such things, although not specifically what you are asking about.