Getting started

suggest change

The 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)

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">&#8676;</button>
<button data-edit="justifyRight">&#8677;</button>
<button data-edit="removeFormat">&times;</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>

jsFiddle demo

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents