-2

I am trying to create a button that is set into a content editable. It does set the text I input to bold however, I only want it to set the highlighted text bold instead of the whole text. Any help would be appreciated.

function bold(){
  const x = document.getElementById("text");
  if(x.style.fontWeight == "bolder"){
    x.style.fontWeight = "normal";
  }else{
    x.style.fontWeight = "bolder";
  }
}

<button onclick="bold()"> B </button>
<div id="text" class="editor" contenteditable="true" draggable="true"></div>
Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • Does this answer your question? [Contenteditable div with bold option](https://stackoverflow.com/questions/41056605/contenteditable-div-with-bold-option) – Blake Mumford Dec 08 '19 at 05:23

1 Answers1

0

Your problem will be solved when you update your code like below :

    <button onclick="bold()"> B </button>
    <div id="text" class="editor" contenteditable="true" draggable="true">Text Example</div>

    <script>
      function bold(){
      if(document.execCommand("bold")){
        document.execCommand("normal");
      }else{
        document.execCommand("bold");
      }
    }
    </script>