How to Select SVG xlink:href Attributes with querySelectorAll()

You have an SVG icon sprite, and you want to find every <use> element that points at a particular icon:

<svg>
  <use xlink:href="#icon-star"></use>
</svg>

None of the obvious selectors work:

document.querySelectorAll('[xlink:href]');    // SyntaxError
document.querySelectorAll('[xlink\\:href]');  // empty NodeList
document.querySelectorAll('[href]');          // empty NodeList (for this element)
document.querySelectorAll('[xlink|href]');    // SyntaxError

Short answer: use the namespace wildcard *|, which matches an attribute in any namespace:

document.querySelectorAll('[*|href]');                    // every href or xlink:href
document.querySelectorAll('use[*|href="#icon-star"]');    // a specific icon
document.querySelectorAll('[*|href]:not([href])');        // xlink:href only

Why the obvious selectors fail

xlink:href looks like an attribute named "xlink:href", but it isn't. When the HTML parser sees it on an SVG element, it creates an attribute whose local name is href, in the XLink namespace (http://www.w3.org/1999/xlink), with xlink as its prefix:

const attr = document.querySelector('use').attributes[0];

attr.name;          // "xlink:href"
attr.localName;     // "href"
attr.prefix;        // "xlink"
attr.namespaceURI;  // "http://www.w3.org/1999/xlink"

Each failed selector trips over this in a different way:

The fix: the *| namespace wildcard

The one namespace form you can use without declaring anything is *|, which means "in any namespace, or none". So [*|href] matches the href attribute whatever namespace it's in:

document.querySelectorAll('[*|href]');

All the usual attribute selector operators work with it:

document.querySelectorAll('use[*|href="#icon-star"]');   // exact value
document.querySelectorAll('use[*|href^="#icon-"]');      // starts with
document.querySelectorAll('use[*|href$="-star"]');       // ends with
document.querySelectorAll('use[*|href*="sprite.svg"]');  // contains

Because it matches plain href as well, [*|href] finds <use> elements whether they were written with the old xlink:href or the newer href. That's usually what you want. It also matches every ordinary HTML link on the page, so qualify it with an element name, as in use[*|href], or run it on the <svg> element instead of the document.

Say you're migrating old markup and want to find the elements that still use xlink:href. Take everything with an href in any namespace, then drop the ones with a no-namespace href:

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

One catch: an element that has both attributes is excluded, because it does have a plain href. If you need those too, filter in JavaScript:

const XLINK = 'http://www.w3.org/1999/xlink';

const withXlink = [...document.querySelectorAll('[*|href]')]
  .filter((el) => el.hasAttributeNS(XLINK, 'href'));

Matching the XLink namespace exactly with XPath

*| matches any namespace, not specifically XLink. In practice that rarely matters, but if you need an exact namespace match in a single query, XPath can do what CSS selectors can't here: it lets you map a prefix to a namespace with a resolver function.

const XLINK = 'http://www.w3.org/1999/xlink';

const result = document.evaluate(
  '//*[@xlink:href="#icon-star"]',
  document,
  (prefix) => (prefix === 'xlink' ? XLINK : null),
  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
  null,
);

const elements = Array.from(
  { length: result.snapshotLength },
  (_, i) => result.snapshotItem(i),
);

Gotcha: setAttribute('xlink:href') creates the wrong attribute

If you create <use> elements in JavaScript, this one bites twice: the icon doesn't render, and your selector doesn't find it.

const use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
use.setAttribute('xlink:href', '#icon-star');
svg.append(use);

use.href.baseVal;                  // "" (the browser doesn't see a link)
svg.querySelector('[*|href]');     // doesn't match this element
svg.querySelector('[xlink\\:href]');  // matches this element

setAttribute() doesn't know about namespaces. If the attribute doesn't already exist, it creates one with no namespace whose local name is literally xlink:href. That's not a link as far as SVG is concerned, and it's also the one case where the escaped [xlink\:href] selector matches.

The fix is to use setAttributeNS(), or better, plain href:

use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#icon-star');

// or, in any current browser:
use.setAttribute('href', '#icon-star');

Note that setAttribute('xlink:href', …) does work on an element that already has a parsed xlink:href: it finds the existing attribute by its full name and updates it. That's why this bug often shows up only on elements you create from scratch.

Gotcha: elements with both href and xlink:href

Some markup includes both attributes for compatibility with older browsers. When they disagree, current browsers use href and ignore xlink:href. But [*|href] matches either attribute, so a selector can match an element because of a value it isn't actually using:

<use href="#icon-star" xlink:href="#icon-heart"></use>
svg.querySelector('use[*|href="#icon-heart"]');  // matches, but it shows the star

If you need to know which icon is actually used, read the element's href property, as described next.

Reading the value

Once you've found the elements, there are three ways to read the value:

use.getAttribute('xlink:href');                                  // "#icon-star"
use.getAttributeNS('http://www.w3.org/1999/xlink', 'href');      // "#icon-star"
use.href.baseVal;                                                // "#icon-star"

getAttribute('xlink:href') works because, unlike a selector, it compares against the attribute's full name, prefix included. use.href.baseVal gives you the value the browser actually uses: href if it's present, otherwise xlink:href. That makes it the best choice when an element might have either, or both.

Should you still be using xlink:href?

For new code, no. SVG 2 lets you write plain href, all current browsers support it, and xlink:href is deprecated. Plain href is a normal attribute, so [href] and setAttribute('href', …) just work.

But xlink:href is still everywhere in existing icon sprites, exported SVG files and older libraries, so you'll keep running into it. Selecting with [*|href] handles both, which makes it a good default.

Try it in your browser

This page contains a hidden SVG with four <use> elements. Press the button to run the selectors from this article against it and see what your browser returns:

<svg id="demo-svg">
  <use id="old"  xlink:href="#demo-star"></use>
  <use id="new"  href="#demo-star"></use>
  <use id="both" href="#demo-star" xlink:href="#demo-heart"></use>
</svg>

// Added by the demo script:
// <use id="script"> created with setAttribute('xlink:href', '#demo-star')
Results will appear here.

Summary