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

226
Views
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
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!