1 votes

how to change SVG color with variables?

Well I was working on a personal project and something happened to me that I do not know if I am really understanding it well, the point is that I am changing the colors of a SVG with a css class which is modified with a JavaScript function this works, the point is that the change only makes it to a single attribute and not to the others with the 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 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. cuando esta por defecto introducir la descripción de la imagen aquí

0voto

enxaneta Points 2355

By making var r = document.querySelector('.color1'); you select only the first element whose class is color1. What you need to do is to select all class1 elements with 'querySelectorAll()' and then iterate the array of class1 elements and change the color.

var rr = document.querySelectorAll(".color1");

function myFunction_set() {
  rr.forEach(r => r.style.setProperty("fill", "#51d426"));
}

svg{border:solid}

<svg width="100%" height="100%" viewBox="0 0 408 70" 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>

<button type="button" onclick="myFunction_set()">cambiar color con js varaible</button>

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X