1

I’d like to wrap a series of <g> elements with <a> elements so they are tabbable. I've tried using jQuery but encountered the namespace problem so have been looking at a more vanilla JS approach. The SVG was created in Illustrator and loaded into the page with an AJAX call. I then use jQuery to bind events etc. I know I can add them in Illustrator with Image Map but I’d like to find a way to get it done programmatically. This is what I’d like to do:

$('g').wrap(function() {
    var anchor = document.createElementNS('http://www.w3.org/2000/svg', 'a');
    anchor.setAttribute('xlink:href', 'javascript:void(0);');

    return anchor;
});

This gets it into the DOM but doesn't render so I'm assuming a namespace problem still. I’m more than likely doing something obviously wrong so any help would be greatly appreciated! Thanks.

Here's a pure JS fiddle (same problem as code above): http://jsfiddle.net/bigwigal/pqe3o93e/.

bigwigal
  • 95
  • 8

1 Answers1

2

If you use SVG <a> elements your content will appear and links will work.

var g = document.getElementById('target');

var parent = g.parentNode;
var a = document.createElementNS('http://www.w3.org/2000/svg', 'a');

a.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'javascript:void(0);');
a.appendChild(g);

parent.appendChild(a);

Not sure if that will make it tabbable but if not you'll need to wrap in an html <a> with an <svg> child as directly wrapping a <g> won't render as you've seen. I.e. you'll need to create something that looks like this... <foreignObject><a><svg><g></g></svg></a></foreignObject> where the <a> is an html element and the others are svg elements.

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
  • Thanks for your response but it doesn't really solve the problem. What I'm looking for is a way to get it to work as if you copy and paste the output to a new fiddle as @Paul S. notes above, resulting in the content within being displayed and tabbable. – bigwigal Dec 09 '14 at 15:16
  • it does work, just took the ns declaration into the jquery fiddle: http://jsfiddle.net/pqe3o93e/2/ – errand Dec 09 '14 at 15:32
  • That's odd, it didn't when I plumbed it into the fiddle in it's original form. It also doesn't in my full code for some reason. My apologies anyway Robert. – bigwigal Dec 09 '14 at 15:47