Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

257
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda