I want to change the background of my text selection using HTML button.
Is there any way to change background color of ::selection (selected text) using JavaScript?
In general where it's not possible to directly change pseudo element settings via JS it is possible to set CSS variables using JS.
So if you have something like this in your stylesheet:
::selection {
background-color: var(--selcolor);
}
and something like this in your JS:
element.style.setProperty('--selcolor', selcolor)
it will work.
Here's small example. It changes the selection color variable in the body:
function selChange(color) {
document.body.style.setProperty('--selcolor', color);
}
body {
--selcolor: yellow;
}
::selection {
background-color: var(--selcolor);
}
<button onclick="selChange('cyan');">Cyan</button>
<button onclick="selChange('magenta');">Magenta</button>
<button onclick="selChange('yellow');">Yellow</button>
<p>Highlight some of this text, then click a color and highlight some text...</p>
Here's example in pure CSS
<!DOCTYPE html>
<html>
<head>
<style>
.body-selection-green *::selection {
background: green;
}
.body-selection-yellow *::selection {
background: yellow
}
</style>
</head>
<body class="body-selection-green">
<div> Try to select me </div>
<button> change selection background</button>
<script>
let btn = document.getElementsByTagName("button")[0];
btn.addEventListener("click", function() {
if(document.body.classList.contains("body-selection-green")) {
document.body.classList.remove("body-selection-green")
document.body.classList.add("body-selection-yellow")
} else if(document.body.classList.contains("body-selection-yellow")) {
document.body.classList.remove("body-selection-yellow")
document.body.classList.add("body-selection-green")
}
});
</script>
</body>
</html>