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

561
Views
How to change the highlight color of selected text in a textarea, using selection range?

I am currently highlighting text in a textarea using a selection range from the Web API. This works fine, however, I would like to change the default highlight color and opacity. I have attempted to change this with css (see example below), however, it does not update the color of the selection. Does anyone know of a way to achieve this?

// select text
const startPosition = 0;
const endPosition = 25;
textarea.setSelectionRange(startPosition, endPosition);

// CSS
textarea::selection {
    background-color: red;
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I don't understand exactly what you want.
Did you want an answer like the code below?
https://codepen.io/jyh7a/pen/xxpLMZZ

HTML

<input type="text" id="text-box" size="20" value="Mozilla">
<button onclick="selectText()">Select text</button>

<hr/>

<textarea rows="6" cols="40">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Porro maxime excepturi autem nostrum minus quae magni, esse optio ab, dolor ut iste earum sapiente molestiae nihil totam rem ipsam officia?</textarea>

<hr/>

<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Porro maxime excepturi autem nostrum minus quae magni, esse optio ab, dolor ut iste earum sapiente molestiae nihil totam rem ipsam officia?</p>

CSS

::selection {
    background-color: rgba(255,0,0,0.2);
}

JS

function selectText() {
  
  const input = document.getElementById('text-box');  
  input.focus();
  input.setSelectionRange(2, 5);

  setTimeout(() => {
    const textarea = document.querySelector('textarea');
    textarea.focus();
    textarea.setSelectionRange(0, 20);
  }, 1000)
  
     
  // // ERROR! 
  // // setSelectionRange function only use HTMLInputElements
  // const p = document.querySelector('p');
  // p.setSelectionRange(0, 20);
}

I searched for setSelectionRange
I made the above example by looking at the MDN official documentation.
(Link: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange )

Hope the above code was helpful to you.

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