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>