Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

229
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda