2

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/

Aidan Young
  • 554
  • 4
  • 15

2 Answers2

4

here is your solution.

function changeBold() {
  const text = window.getSelection().toString();
  var span = document.createElement('span');
  span.innerHTML = text;
  span.style.fontWeight = 'bold';
  document.execCommand('insertHTML', false, span.outerHTML);
}
<p contenteditable="true" id="contenttxt">
  Some text in this paragraph tag
</p>
<button onclick="changeBold()">Bold selected text</button>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • This still works, but note that [execCommand is deprecated](https://stackoverflow.com/questions/60581285/execcommand-is-now-obsolete-whats-the-alternative) – mplungjan Aug 17 '23 at 12:58
1

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>
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • This does bold the first two words of the content editable

    tag however the first two words was an example. What I was looking for is a way to bold the selected text. For example, if the last two words are selected, it will bold the last two words. If the middle word is selected, it will bold the middle word.

    – Aidan Young Dec 15 '21 at 17:11