2

I am trying to add an xlink:href attribute to an SVG element from JS, but it's not working.

Here is my code:

test.html:

<html>
    <head>
        <script type="text/javascript" src="test.js"></script>
    </head>
    <body onload=setupSvgLink()>
        <object id="test-svg" type="image/svg+xml" data="test.svg" />
    </body>
</html>

test.js:

function setupSvgLink() {
    var svg = document.getElementById("test-svg").contentDocument;
    var waldo = svg.getElementById("waldo");
    waldo.setAttribute("xlink:href", "waldo.html");
}

test.svg:

<?xml version="1.0" standalone="no"?>
<svg version="1.0" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="80">
    <a id="waldo"><rect x="10" y="10" width="60" height="60" fill="blue"/></a>
</svg>

I am testing this with Firefox 20. I load test.html, but the rectangle does not have a link on it. I have checked in the Firefox Developer Tools' Inspector that the xlink:href attribute does appear on the element, but there is no link.

If I add the xlink:href attribute into the SVG file instead of doing it via JS it works fine.

What am I doing wrong?

0

1 Answer 1

2

When dealing with SVG you usually need to use element.setAttributeNS, change your function...

function setupSvgLink() {
    var xlinkns="http://www.w3.org/1999/xlink";
    var svg = document.getElementById("test-svg").contentDocument;
    var waldo = svg.getElementById("waldo");
    waldo.setAttributeNS(xlinkns, "href", "waldo.html");
}
Sign up to request clarification or add additional context in comments.

2 Comments

That worked with one modification: the namespace needed to be http://www.w3.org/1999/xlink. Thanks!
@HighCommander4 Ah now I see, I've modified the answer. When changing SVG attributes preceded by a namespace (such as xlink) you use the corresponding namespace. Otherwise it's the SVG namespace. You learn something new every day!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.