Reputation: 328
I am looking for a way to change the style of the text highlighted from the user. For example when the user highlights text with their mouse and clicks a button, I want the text that is selected to change even after it is not being highlighted anymore like a rich text editor. I tried to store the highlighted text into a variable and change the styles with the javascript DOM style property but it it returns an error. Here is my code so far
document.addEventListener('mouseup', event => {
if(window.getSelection().toString().length){
let exactText = window.getSelection().toString();
}
}
It can console.log
the text that is highlighted but it can't change the styles. Thank you for your help
Upvotes: 1
Views: 745
Reputation: 1
solution with css
.element::selection{
background: red
}
<div class="element">foo bar</div>
Upvotes: 0