0

I'm trying to apply H1 on the selected text. but when I select some text it applies to all text.

All I need to apply H1 for just selected text, not for all text. I need to get selected text and replace it with an element not just to get the selected text.

function exec(){
    document.execCommand('formatblock', false, 'h1');
}
#ce{
  height: 100px;
  border: solid 1px black;
  padding: 10px;
}
<button onclick="exec()">apply H1</button>
<div id="ce" contenteditable></div>
MOHAMED ABUELATTA
  • 305
  • 2
  • 5
  • 15
  • 2
    Does this answer your question? [Get the Highlighted/Selected text](https://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text) – Simone Rossaini Sep 01 '21 at 11:23

2 Answers2

2

You can add this code and once the selected text will be made bold and if it's already bold, the text styling will be removed.

  $(function() {
      $(".btn").click(function() {
        var command = $(this).data("command");
          const selection = window.getSelection();
          document.execCommand("insertHTML",false,`<${command}>${selection}</${command}>`);
      });
    });
#ce{
  height: 100px;
  border: solid 1px black;
  padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <button data-command="h1"  class="btn btn-default btn-sm">apply H1</button>
<div id="ce" contenteditable></div>
1

Here is how to wrap selected text from contenteditable with your chosen tag.

function wrapSelectedText(wrappingTag) {
    var highlightedText, range, replacementNode;
    if (window.getSelection) {
        // get highlightedText
        highlightedText = window.getSelection();
          // prepare Node to for replacement
          const Element = document.createElement(wrappingTag);
          const TextNode = document.createTextNode(highlightedText.toString());
          Element.appendChild(TextNode);
        // delete text and insert replacement
        if (highlightedText.rangeCount) {
            range = highlightedText.getRangeAt(0);
            range.deleteContents();
            range.insertNode(Element);
        }
      // for IE
      /*
      } else if (document.selection && document.selection.createRange) {
          range = document.selection.createRange();
          range.text = replacementText;
      }
      */}
}
#ce{
  height: 100px;
  border: solid 1px black;
  padding: 10px;
}
<button onclick="wrapSelectedText('h1')">Wrap Selection</button>
<div id="ce" contenteditable></div>
MOHAMED ABUELATTA
  • 305
  • 2
  • 5
  • 15