Cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Dynamically change href of <use>

Hello,

 

Is it possible to change the href of a <use> element during runtime? I'd like to change the href to reference a different symbol.

 

Example:

 

<defs>
  <symbol id="heart1">
    <image href="heart1.png"/>
  </symbol>
  <symbol id="heart2">
    <image href="heart2.png"/>
  </symbol>
</defs>
<use id="heartrate" href="#heart1" />
var hr = document.getElementById('heartrate');
hr.href="#heart2";

Based on my tests, this doesn't appear to be possible, but I wanted to make sure I wasn't approaching it incorrectly.

 

Thanks,

Nick

Best Answer
2 REPLIES 2

I'm facing the same problem while trying to create a clock face with custom numbers in pure SVG instead of using PNGs. I already have the SVG code for all the numbers and put them into 10 symbols. But just like OP I'm unable to change the href of my <use> elements in JS. I've tried:

 

myUse.href = "mySymbol";
myUse.setAttribute("href", "mySymbol");
myUse.setAttributeNS("http://www.w3.org/1999/xlink", "href", "mySymbol");

None of this works. Are we missing something or is it simply not possible atm? Thanks!

Best Answer

Hi. I am also facing the same issue. I have tried the following:

 

 

let item1 = document.getElementById("item1");

item1.style['xlink:href']="#anything";
item1['xlink:href']="#anything";
item1.xlink="#anything";
item1.href="#anything";
item1.style.href="#anything";
item1.style.xlink.href="#anything";

 

Any ideas? Thanks.

 

 

Best Answer