Francisco Costa
Francisco Costa

Reputation: 379

How to change css pseudo-element through javascript?

My webpage randomly generates a color, and some elements, like inputs, get colors generated as border or so through javascript. Something like this:

document.getElementById('input').style.color = color;

The thing is I want a thumb from <input type="range" /> to get the random color generated and I don't know how to do it, tried and searched the web without finding a solution to get this css style input[type=range]::-webkit-slider-thumb in javascript.

Can anyone help me please? Thanks in advance.

Upvotes: 0

Views: 429

Answers (2)

Francisco Costa
Francisco Costa

Reputation: 379

Well I finally did it, I don't know if what I did is good programming but anyway it works, I needed to add a css rule so by doing this:

document.styleSheets[0].insertRule('input[type=range]::-webkit-slider-thumb 
{ background-color:' + color + ' !important; }', 0);

I was able to finally manipulate the pseudo-element (at least in chrome, next step other major browsers). Anyway I think this is helpful to someone who wants to try something like this, I needed to search and tried many things to do this.

Thanks to everyone who tried to help me.

Upvotes: 1

imbondbaby
imbondbaby

Reputation: 6411

The simplest way to change the style of a pseudo-element is by adding and removing classes in JavaScript or JQuery. Here is an example:

CSS:

.newClass::-webkit-slider-thumb{
    color:red;
}

JS Solution:

To add class:

document.getElementById("selector").classList.add('newClass');

To remove class:

document.getElementById("selector").classList.remove('newClass');

JQuery Solution:

To add class:

$("#selector").addClass("newClass");

To remove class:

$("#selector").removeClass("newClass");

Upvotes: 1

Related Questions