ngplayground ngplayground - 1 month ago 8
jQuery Question

jQuery selector by xlink

$('a[xlink\\:href=#coastline]').attr('class','grey');
$('a[xlink\\:href=#onshore]').attr('class','blue-light');


This is what I currently have to select each item that has the xlink of
#coastline
and turn it grey and turn
#onshore
to
blue-light


How would I be able to change the above to select any
a[xlink\\:href]
and give it a class?

I have tried
$('a[xlink:href]').attr('class', 'yellow');
but this doesn't give them a class of
yellow

Answer

xlink can be found in xml tags and are tricky to select as they are in another namespace.

You can try to loop through all the elements and modify the DOM element className

var $elements = $('a[xlink\\:href]');
$elements.each(function(index, element) {
    element.className = 'my-new-class';
});

UPDATE: The current selector should returns null as it's an issue of namespace. We can fix this namespace using the special selector a[*|xlink] Stack Overflow post reference

We know that it's SVG, so to change SVG object classes, we have to use attr function on them. If you just want to select all the links inside your SVG elements I'd got with something like this:

var $svg = $('svg');
var $elements = $('a[*|xlink]', $svg);  // Select all a xlink attributes inside svg object


$elements.each(function(index, element) {
    $(element).attr('class', 'my-new-class');  // force class attribute
});

JSFiddle: http://jsfiddle.net/nbfdydzd/

Comments