Search code examples
javascripthtmladdeventlistenercontenteditablebold

How to set the bold button to only highlight selected text?


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>

Solution

  • 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>