Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i change svg attributes with js?

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

here is what i want to do:

what i want to do

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

here is what I did:

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading