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

228
Visualizações
How can I give styling to selected text in textarea in a basic text editor?

I want to build a unique, simple text editor. With this JS code I can get the selected text from the textarea, but how may I give styling to it (font-weight, font-style etc.) with buttons (Bold, Italic)?

    var selectedText = '';

    function getText(e) {
        selectedText = (document.all) ? document.selection.createRange().text : document.getSelection();

        alert(selectedText);
    }

    document.onmouseup = getText;
    if (!document.all) document.captureEvents(Event.MOUSEUP);

I experimented with adding the following code into the getText function. It works at some point, the selected text is wrapped into a span, the span gets the .new-span, bold-style and italic-style classes (btn onclick), but still the styling does not apply to the selected text in the textarea, the change is not visible.

     var selectedText = '';

    function getText(e) {
        selectedText = (document.all) ? document.selection.createRange().text : document.getSelection();

        var newSpan = document.createElement("span");
        newSpan.classList.add("new-span");
        newSpan.innerText += selectedText;
        console.log(newSpan);
        artParag.appendChild(newSpan);
        var boldStyleBtn = document.querySelector(".bold-style-btn");
        var italicStyleBtn = document.querySelector(".italic-style-btn");

        boldStyleBtn.addEventListener("click", function boldStyle() {
            newSpan.classList.toggle("bold-style");
            alert(selectedText);
        });

        italicStyleBtn.addEventListener("click", function italicStyle() {
            newSpan.classList.toggle("italic-style");
            alert(selectedText);
        });
    }

    document.onmouseup = getText;
    if (!document.all) document.captureEvents(Event.MOUSEUP);

(the CSS):

.bold-style {
    font-weight: 700;
}

.italic-style {
    font-style: italic;
}

Is this a good direction? Thank you in advance for your help.

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