1
$('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

ngplayground
  • 20,365
  • 36
  • 94
  • 173

5 Answers5

2

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/

Community
  • 1
  • 1
lovethebomb
  • 283
  • 5
  • 12
  • `Uncaught Error: Syntax error, unrecognized expression: a[xlink:href]` – ngplayground Sep 24 '14 at 09:01
  • I guess you have to escape it as you typed in your original post above with slashes. You might want to check this post about XML/SVG namespaces and selectors http://stackoverflow.com/questions/23034283/is-it-possible-to-use-htmls-queryselector-to-select-by-xlink-attribute-in-an – lovethebomb Sep 24 '14 at 09:02
1

You need to escape special characters

$('a[xlink\\:href]').attr('class', 'yellow');
Icepick
  • 159
  • 1
  • 10
1

From your comment i'm thinking that you have smth like

 <a xlink:href="http://www.google.com" target="_blank">
     <text x="0" y="15" fill="red">Link text here</text>
 </a>

So, to change it's color you can try to change it's fill attribute like

 $('a[xlink\\:href=#coastline]').attr('fill','#ff00ff');
Y.Puzyrenko
  • 2,166
  • 1
  • 15
  • 23
1

[*|href] will match both html href and svg xlink:href, then use :not([href]) to exclude html href.

//document.querySelectorAll('[*|href]:not([href])');
$('[*|href]:not([href])');

tested in chrome

cuixiping
  • 24,167
  • 8
  • 82
  • 93
0

Maybe this is what you want Demo

$('a').each(function(i){
    if($(this).attr('href') == "#coastline") $(this).addClass('gray');
    if($(this).attr('href') == "#onshore") $(this).addClass('green');
    if($(this).attr('href') == "") $(this).addClass('yello');
});
jogesh_pi
  • 9,762
  • 4
  • 37
  • 65