HTML DOM execCommand() method


The HTML DOM execCommand() method is used for executing a command specified on the editable section that is being selected by the user. The document.design property should be set to have an editable section in the first place.

Syntax

Following is the syntax for the execCommand() method −

document.execCommand(command, showUI, value)

Here, value is for some specific commands that needs to be completed, such as, fontSize, forecolor, etc. The showUI is a boolean value for specifying if the value should be shown or not. The command name is the command that needs to be executed on the editable section.

Following are the values for the command parameter −

"backColor", "bold", "createLink", "copy", "cut", "defaultParagraphSeparator", "delete",
"fontName", "fontSize", "foreColor", "formatBlock", "forwardDelete", "insertHorizontalRule",
"insertHTML", "insertImage", "insertLineBreak", "insertOrderedList", "insertParagraph",
"insertText", "insertUnorderedList", "justifyCenter", "justifyFull", "justifyLeft",
"justifyRight", "outdent", "paste", "redo", "selectAll", "strikethrough", "styleWithCss",
"superscript", "undo", "unlink", "useCSS"

Example

Let us look at an example for the execCommand() method −

Live Demo

<!DOCTYPE html>
<html>
<body ondblclick="changeText()">
<h1>execCommand() method example</h1>
<h3>double click on any text to change its fontsize and color</h3>
<p>Here is some text for being clicked upon. Some sample text is here too </p>
<script>
   document.designMode = "on";
   function changeText() {
      document.execCommand("fontSize",true,"20px");
      document.execCommand("backColor",true,"lightgreen");
      document.execCommand("foreColor",true,"blue");
}
</script>
</body>
</html>

Output

This will produce the following output −

On double clicking some text on the page, the formatting of that particular text will change −

In the above example −

We have first associated an event handler with our document body for the double click event. On double clicking any of the body children, it will execute the changeText() method. The body children here are the h1, h3 and p elements −

<body ondblclick="changeText()">

We first set the document design mode to on so that we can edit our document. The function changeText() executes the execCommand() method of the document and passes its parameters like fontSize, backColor, foreColor along with their respective values. These values will be applied to the editable section double clicked by the user −

Function changeText() {
document.execCommand("fontSize",true,"20px");
document.execCommand("backColor",true,"lightgreen");
document.execCommand("foreColor",true,"blue");

Updated on: 19-Feb-2021

668 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements