Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing css fill for svg with JS

I'm trying to change svg fill color, which is defined with css, using JS. For some reason it doesn't work. Here is my code:

SVG itself (in short):

<svg id="secondalert"><style>.cls-1{fill:#000000;}</style></svg>

And JS to target and change it:

function() {
    var svg_css = document.getElementsByClassName('.cls-1');

    if (random_value < 20) {
        svg_css.css({
            "fill": "#EF4136"
        });

    } else {
        svg_css.css({
            "fill": "#EF4136"
        });
    }
}

Something is not coming together, a fill color stays black as it is in style tag. What am I doing wrong?

like image 611
Nebular Dust Avatar asked Sep 15 '25 17:09

Nebular Dust


1 Answers

Instead of using svg_css.css({"fill" : "#hexadecimal"}) you can use svg_css.style.fill = "#hexadecimal"

And also, when you use getElementsByClassName it returns an array, instead use getElementById or choose the element inside array:

svg_css = document.getElementsByClassName('.cls-1')[0];
like image 133
Luis Machillanda Avatar answered Sep 18 '25 09:09

Luis Machillanda