well I was working on a personal project and something happened to me that I don't know if I'm really understanding it correctly, the point is that I am changing the colors of an SVG with a css class which is modified with a JavaScript function this works, the point is that the change is only made to a single attribute y and not to the others with that same class:
<svg width="100%" height="100%" viewBox="0 0 408 303" fill="none" xmlns="http://www.w3.org/2000/svg">
<style>
.color1 {fill:#8a6dc0}
</style>
<g id="TRESX31">
<rect width="408" height="303" fill="white"/>
<rect id="Rectangle1" x="10" y="16" width="40" height="40" fill="#858585"/>
<rect id="Rectangle2" x="59" y="16" width="40" height="40" class="color1"/>
<rect id="Rectangle3" x="108" y="16" width="40" height="40" class="color1"/>
<rect id="Rectangle4" x="157" y="16" width="40" height="40" fill="#EAAF16"/>
<rect id="Rectangle5" x="206" y="16" width="40" height="40" class="color1"/>
</g>
</svg>
and I modify the color with the following function:
<script>
var r = document.querySelector('.color1');
function myFunction_set() {
r.style.setProperty('fill','#51d426');
}
</script>
<button type="button" onclick="myFunction_set()">cambiar color con js varaible</button>
and I need the change to be made for everyone, I hope you can help me and that the information is accurate.
By doing
var r = document.querySelector('.color1');
you select only the first element whose class is color1. What you need to do is select all class1 elements with 'querySelectorAll()' and then iterate through the array of class1 elements and change the color.