How to mark text between elements with editable contents?

by Vijay Pancholi

HTML

<div contenteditable="true" class="edit-div">Lorizzle ipsizzle dolizzle sit amizzle, shizzlin dizzle yippiyo elit. Nullam dizzle velizzle, for sure volutpizzle, suscipit shizzle my nizzle crocodizzle, gravida vizzle, izzle. Pellentesque egizzle tortor. <b>Sizzle eros. yo dolor dapibizzle boom shackalack shiz tempor.</b> <i>Maurizzle pellentesque nibh izzle yo. Gangsta izzle tortor. Pellentesque eleifend rhoncizzle own yo'.</i> In crazy get down get down owned dictumst. Fo shizzle mah nizzle fo rizzle, mah home g-dizzle dapibizzle. Boofron tellizzle urna, pretium eu, mattizzle ac, eleifend vitae, hizzle. Dang suscipizzle. Boofron semper velit fizzle its fo rizzle.</div>
<div contenteditable="true" class="edit-div">Lorizzle ipsizzle dolizzle sit amizzle, shizzlin dizzle yippiyo elit. Nullam dizzle velizzle, for sure volutpizzle, suscipit shizzle my nizzle crocodizzle, gravida vizzle, izzle. Pellentesque egizzle tortor. <b>Sizzle eros. yo dolor dapibizzle boom shackalack shiz tempor.</b> <i>Maurizzle pellentesque nibh izzle yo. Gangsta izzle tortor. Pellentesque eleifend rhoncizzle own yo'.</i> In crazy get down get down owned dictumst. Fo shizzle mah nizzle fo rizzle, mah home g-dizzle dapibizzle. Boofron tellizzle urna, pretium eu, mattizzle ac, eleifend vitae, hizzle. Dang suscipizzle. Boofron semper velit fizzle its fo rizzle.</div>

<button onclick="markText()">Mark</button>

CSS

.edit-div {
  border: 1px solid;
  margin: 20px;
  width: 400px;
}

JavaScript

function markText() {
  // Check if the browser supports document.execCommand
  if (document.queryCommandSupported('hiliteColor')) {
    // Get the selected text
    var selection = window.getSelection();

    // Check if there is a non-empty selection
    if (selection.rangeCount > 0) {
      var range = selection.getRangeAt(0);

      // Use execCommand to highlight the selected text
      document.execCommand('hiliteColor', false, 'yellow');

      // Clear the selection
      selection.removeAllRanges();
    }
  } else {
    console.error('The browser does not support document.execCommand');
  }
}