Search code examples
javascriptcsssvgfill

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?


Solution

  • 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];