How do i change svg attributes with js?

Advertisements

Today I got some problems changing the attributes of a svg with js using the onclick method;

here is what i want to do:

here is what I did:

(there is the arrow, but the grey covers it)


Here is my code:

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>

>Solution :

With document.getElementById("arrow") you are searching the <svg> element.
Then you are changing its fill attribute, but the fill attribute of the <path /> element overwrites it. So you have to either move id="arrow" from the <svg> to the path move the fill from the <path /> to the <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>

or

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>

Leave a ReplyCancel reply