Javascript DOM HTML Document execCommand() Method

Introduction

Make the selected text bold:

document.execCommand("bold");

The executeCommand() method executes a specified command on selected text or section.

View in separate window

<!DOCTYPE html>
<html>
<body onkeydown="myFunction(event)">

<h1>Document execCommand() Method</h1>
<h2>Select Text and Press Shift</h2>
<p>Select some text in this page, and press the SHIFT button to make the selected text toggle between bold and normal.</p>

<script>
document.designMode = "on";

function myFunction(event) {/*w w  w .  j a v  a 2 s . com*/
  if (event.keyCode == 16) {
    // Execute command if user presses the SHIFT button:
    document.execCommand("bold");
  }
}
</script>

</body>
</html>

The execCommand() method executes the specified command for the selected part of an editable section.

document.execCommand(command);

Parameter Values

Value Description
command Specifies the name of the command to execute on the selected section.
showUI A Boolean, specifies if the UI should be shown or not
value Some commands need a value to be completed

command values:

  • 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
  • subscript
  • superscript
  • undo
  • unlink
  • useCSS

The executeCommand() method returns false if the command is not supported, otherwise true.




PreviousNext

Related