Не работает execCommand

$(".options-wrapp span").on('click', function(e) {

  e.preventDefault();
  document.execCommand($(this).data('role'), false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="options-wrapp">
    <span class="option bold" data-role='bold'>
            <i class="fa fa-bold" aria-hidden="true">bold</i>
    </span>
<span class="option italic" data-role='italic'>
        <i class="fa fa-italic" aria-hidden="true">italic</i>
    </span>
<span class="option image">
        <i class="fa fa-picture-o" aria-hidden="true">image</i>
    </span>
</span>

Пример кода откуда брал(там работает) - https://codepen.io/souporserious/pen/xBpEj


Ответы (1 шт):

Автор решения: Stepan Kasyanenko

Не работает, потому что вы не полностью\не правильно скопировали пример.

Обратите внимание:

  1. execCommand - должен выполняться над выделенным текстом. Данный текст должен находится в блоке с contenteditable.
  2. Обработчик нажатия, где вы будете вызывать execCommand, должен находится на элементе, который кликабельный, например a или button.

$(".options-wrapp button, .options-wrapp a, .options-wrapp span").on('click', function(e) {
  console.log($(this).data('role'));
  e.preventDefault();
  document.execCommand($(this).data('role'), false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <span class="options-wrapp">
    <a  href='#' class="option bold" data-role='bold'>bold</a>
    <button class="option italic" data-role='italic'>
        <i class="fa fa-italic" aria-hidden="true">italic</i>
    </button>
    <span class="option image" data-role='underline'>
        <i class="fa fa-picture-o" aria-hidden="true">underline</i>
    </span>
  </span>
  <div contenteditable>
    <b>Let's make a statement!</b>
    <br>
    <i>This is an italicised sentence.</i>
    <br>
    <u>Very important information.</u>
  </div>
</div>

→ Ссылка