Hoy tuve algunos problemas para cambiar los atributos de un svg con js usando el método onclick ;
esto es lo que quiero hacer:
Aquí esta lo que hice:
( Ahí está la flecha, pero el gris la tapa )
Aquí está mi código:
function social() { document.getElementById("svg1").style.backgroundColor = "grey"; document.getElementById("arrow").setAttribute("fill", "#ff00ff") } <div id="svg1"> <svg id="arrow" onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13"> <path fill="#6E8098" d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" /> </svg> </div>Con document.getElementById("arrow") está buscando el elemento <svg> .
Entonces está cambiando su atributo de fill , pero el atributo de fill del elemento <path /> lo sobrescribe. Por lo tanto, debe mover id="arrow" desde <svg> a la path mover el fill desde <path /> a <svg>
function social() { document.getElementById("svg1").style.backgroundColor = "grey"; document.getElementById("arrow").setAttribute("fill", "#ff00ff") } <div id="svg1"> <svg onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13"> <path id="arrow" fill="#6E8098" d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" /> </svg> </div>o
function social() { document.getElementById("svg1").style.backgroundColor = "grey"; document.getElementById("arrow").setAttribute("fill", "#ff00ff") } <div id="svg1"> <svg id="arrow" onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13" fill="#6E8098"> <path d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" /> </svg> </div>Recomiendo usar una clase CSS y luego usar classlist.toggle para moverlo al hacer clic:
function social() { document.getElementById("arrow").classList.toggle('active'); } .active { background: grey; border-radius: 30px; padding: 10px; } .active > path { fill: white; } <div id="svg1"> <svg id="arrow" onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13"> <path id='path' fill="#6E8098" d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" /> </svg> </div>