Nebular Dust
Nebular Dust

Reputation: 403

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?

Upvotes: 4

Views: 13109

Answers (2)

Luis Machillanda
Luis Machillanda

Reputation: 111

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

Upvotes: 2

Namaskar
Namaskar

Reputation: 2109

Before we get to changing the style, there are a few things to watch out for:

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

Getting elements by class name is fine, but the . selector is specific to CSS. This means that svg_css will be set to any elements with the class of .cls-1 NOT cls-1.

Secondly, There are no elements with the class of cls-1 in your HTML. An element with such class would look like:

<svg id="secondalert" class="cls-1"></svg>

I'm guessing random_value is declared somewhere else, but you probably want a random value within that function.

What you need to do is get the elements by class name, then since that returns a list of elements, select which one you want (in our case the first one.) Then, to set the fill, use the style property which has a fill property.

var elements = document.getElementsByClassName('cls-1');
elements[0].style.fill = Math.random()*40 > 20 ? "blue" : "red";
<svg class="cls-1" width="100" height="100" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1417 1632h-1118v-480h-160v640h1438v-640h-160v480zm-942-524l33-157 783 165-33 156zm103-374l67-146 725 339-67 145zm201-356l102-123 614 513-102 123zm397-378l477 641-128 96-477-641zm-718 1471v-159h800v159h-800z"/></svg>

Upvotes: 0

Related Questions