javascriptexeccommand

Use span instead of font in execCommand


How to let execCommand using span and style attribute to styling in rich text instead of font tag and color attribute?

This is a simple example for what I need.

Output using execCommand: <font color="#ff0000">Lorem ipsum</font>.

Which outputs:<span style="color:#ff0000">Lorem ipsum</span>.

function exec(a, b) {
  document.execCommand(a, false, b);
  console.log(document.getElementById('editor').innerHTML);
}
#editor {
  box-shadow: 0 0 .3rem #aaa;
  padding: .5rem 1rem;
  margin: .5rem 0;
  min-height: 3rem;
}
<select onchange="exec('forecolor',this.value); this.selectedIndex=0;">
  <option class="heading" selected>- color -</option>
  <option value="red">Red</option>
  <option value="blue">Blue</option>
  <option value="green">Green</option>
  <option value="black">Black</option>
</select>
<div contenteditable="true" id="editor">
  Lorem ipsum
</div>


Solution

  • I found the right way to do that, I wanted to share it. The solution was very easy, is just using document.execCommand("styleWithCSS", true, null);