How to check if selected text is bold or not (contenteditable)

I am using a custom text editor using the built in contenteditable

html function . I need to know when a user has selected text in a text editor, whether it is bold or not.

Here's what I have right now:

Html

<button onclick="boldit()">B</button>
<div id="editor" contenteditable="true" class="email-body">
    This is an <strong>editable</strong> paragraph.
</div>

      

Javascript

function boldit(){
 document.execCommand('bold');
}

      

+3


source to share


2 answers


jQuery(function($) {
    $('.embolden').click(function(){
        if(selectionIsBold()){
          alert('bold');
        }
        else {
          alert('not bold');
        }
    });
});

function selectionIsBold() {
    var isBold = false;
    if (document.queryCommandState) {
        isBold = document.queryCommandState("bold");
    }
    return isBold;
}
      

.bold {
    font-weight: bold;
}
      

<div contenteditable="true" class="textEditor">Some <span class="bold">random </span>text.</div>
<a href="#" class="embolden">Is Bold Text</a>
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
      

Run codeHide result




Highlight the text and click the link.

+2


source


The reliable way is to pass the getComputedStyle parent tree check.

I am assuming you already have the selected item.



function isBold(_element) {
  var element = _element;
  while (element) {
    var style = getComputedStyle(element).fontWeight;
    if (Number(fontWeight) > 400 || fontWeight === 'bold' || fontWeight === 'bolder') {
      return true;
    }
    element = element.parentNode;
  }
  return false;
}

      

+3


source







All Articles