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

258
Views
Only apply styling to selected text in content editable <p>

Problem

Hi, I have some code that when a button is clicked, all of the content in a contentEditable <p> tag will have a font-weight of 600 (bold).

What I'm wondering is how can I make it so when the button is pressed, rather than style all the content in the p tag to 600 font weight, only style the selected text. For example, if you only highlight the first two words of the p tag and press the button, only the first two words will have their font-weight changed.

Image example

In the example, when the button is pressed, only the first two words would have their font-weight changed.

Link to the fiddle containing code: https://jsfiddle.net/AidanYoung/9tg4oas5/

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

here is your solution.

function changeBold() {
    const   text = window.getSelection().toString();
    var btn = document.createElement('span');
    btn.innerHTML = text;
    btn.style.fontWeight = 'bold';
    document.execCommand('insertHTML', false, btn.outerHTML);
    
}
    <p contenteditable="true" id="contenttxt">
      Some text in this paragraph tag
    </p>
    <button onclick="changeBold()">Bold selected text</button>

about 4 years ago · Juan Pablo Isaza Report

0

You can use the span label and add ID

function changeBold() {
    document.getElementById("strongC").style.fontWeight = "600";
}
<p contenteditable="true" id="contenttxt">
    <span id="strongC">Some text</span>
    in this paragraph tag
</p>
<button onclick="changeBold()">Bold selected text</button>

about 4 years ago · Juan Pablo Isaza 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!