Getting started
suggest changeThe HTML attribute contenteditable provides a simple way to turn an HTML element into a user-editable area.
<div contenteditable>You can <b>edit</b> me!</div>
Native Rich-Text editing
document.execCommand can apply editing commands to the focused contenteditable element, at the caret or the selection. The method is deprecated, needs a user gesture, and can return false. The W3C editing spec documents the old command set.
execCommand accepts three arguments:
document.execCommand(commandId, showUI, value)
commandIdis a string from the browser's editing command set, such as"bold".showUIis a boolean. The UI flag is not implemented; passfalse.valueis a string when the command needs one, and""otherwise.
Example using the "bold" command and "formatBlock" (where a value is expected):
document.execCommand("bold", false, ""); // Make selected text bold
document.execCommand("formatBlock", false, "H2"); // Make selected text Block-level <h2>
Quick Start Example:
<button data-edit="bold"><b>B</b></button>
<button data-edit="italic"><i>I</i></button>
<button data-edit="formatBlock:p">P</button>
<button data-edit="formatBlock:H1">H1</button>
<button data-edit="insertUnorderedList">UL</button>
<button data-edit="justifyLeft">⇤</button>
<button data-edit="justifyRight">⇥</button>
<button data-edit="removeFormat">×</button>
<div contenteditable><p>Edit me!</p></div>
<script>
[].forEach.call(document.querySelectorAll("[data-edit]"), function(btn) {
btn.addEventListener("click", edit, false);
});
function edit(event) {
event.preventDefault();
var cmd_val = this.dataset.edit.split(":");
document.execCommand(cmd_val[0], false, cmd_val[1]);
}
</script>
Basic Rich-Text editor example (Modern browsers)
Final thoughts
execCommand has been around since IE6, and its behavior still differs across browsers, so a fully featured cross-browser WYSIWYG editor is hard to build on it. For anything beyond these commands, use a maintained rich-text editor rather than relying on this deprecated API.