Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

451
Views
How to check, the selected text is bold or not (contenteditable)

I'm implementing a custom text editor using html inbuilt contenteditable feature. I need to know when user selected a text on the text editor whether it's bold or not.

Here 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');
}
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

The reliable way is to traverse the parent tree checking getComputedStyle.

I'll assume you have the selected element(s) already.

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;
}
about 4 years ago · Santiago Trujillo Report

0

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>

Highlight the text and click on the link.

about 4 years ago · Santiago Trujillo Report

0

Just call isSelectionBold() :)

Demo on CodePen

function isSelectionBold() {
  var sel;
  if (window.getSelection) { 
    sel = window.getSelection(); 
  } 
  else if (document.getSelection) { 
    sel = document.getSelection(); 
  }
  
    var raw_html = getSelectionAsHtml();
  
  // This is if nothing is selected
  if(raw_html==="") return false;

  var tempDiv = document.createElement('div');
  tempDiv.innerHTML = raw_html;
    
  var is_bold_nodes = []
    for (var node of tempDiv.childNodes) {
    var tags = [node.nodeName.toLowerCase()];
        
    // This covers selection that are inside bolded characters
    while(tags.includes("#text")) {
      var start_tag = sel.anchorNode.parentNode.nodeName.toLowerCase();
      var end_tag = sel.focusNode.parentNode.nodeName.toLowerCase();
      
            tags = [start_tag, end_tag]
    }

        is_bold_nodes.push(containsOnly(['strong', 'b'], tags));
    }
    
    return (! is_bold_nodes.includes(false))
}

function getSelectionAsHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}

function containsOnly(array1, array2){
  return !array2.some(elem => !array1.includes(elem))
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!