Querying the Shapes Inside an SVG <use> Element with querySelectorAll()

Your icons come from an SVG sprite, and each button shows one with <use>:

<svg style="display: none">
  <symbol id="icon-menu" viewBox="0 0 10 10">
    <rect class="bar" y="1" width="10" height="2"/>
    <rect class="bar" y="4" width="10" height="2"/>
    <rect class="bar" y="7" width="10" height="2"/>
  </symbol>
</svg>

<button id="menu-button">
  <svg width="24" height="24"><use href="#icon-menu"/></svg>
</button>

The three bars are on screen, but you can't select them:

document.querySelectorAll('#menu-button rect').length;  // 0
document.querySelector('#menu-button use').children;    // HTMLCollection []
document.querySelector('#menu-button use').shadowRoot;  // null

Short answer: the shapes you see are copies that the browser keeps in a hidden shadow tree, and no DOM API can reach them. Query the original element that the <use> points to instead:

const use = document.querySelector('#menu-button use');
const source = document.getElementById(use.href.baseVal.slice(1));  // the <symbol>

source.querySelectorAll('rect');  // NodeList(3) [rect.bar, rect.bar, rect.bar]

Why the shapes aren't in the DOM

The SVG 2 spec defines <use> as a shadow host. When the browser renders it, it clones the referenced element (here the <symbol> and its <rect>s) into a shadow tree attached to the <use>, and draws the clones. The clones are kept in sync with the original: change the original and every copy updates.

document.querySelectorAll() never looks inside shadow trees, which rules out the copies straight away. With an ordinary web component you would query element.shadowRoot instead, but the <use> shadow tree belongs to the browser and is closed: use.shadowRoot is null. Older specs had an instanceRoot property that exposed the copies, but it was removed and doesn't exist in Chromium 159 or Firefox 159. As far as your scripts can tell, a <use> element has no children at all.

Querying the original element

Since the copies always match the original, query the original. Read the <use>'s link with use.href.baseVal, which works whether the markup uses href or the older xlink:href (see how to select SVG xlink:href attributes with querySelectorAll()), then look up the ID:

function getUseSource(use) {
  const url = new URL(use.href.baseVal, document.baseURI);

  if (url.href.split('#')[0] !== document.URL.split('#')[0]) {
    return null;  // the icon is in another file
  }

  return document.getElementById(decodeURIComponent(url.hash.slice(1)));
}

const source = getUseSource(document.querySelector('#menu-button use'));

source.id;                        // "icon-menu"
source.querySelectorAll('.bar');  // NodeList(3)

Use getElementById() rather than passing the link to querySelector(). A link like /icons.svg#menu isn't a valid selector and throws a SyntaxError, and IDs that start with a digit need escaping in a selector but not in getElementById().

Remember that the original is shared. Changing it, for example source.querySelector('.bar').remove(), changes every <use> that shows this icon, not just the one in your button.

Finding every <use> that shows an icon

The reverse question, "where is this icon used?", is a normal attribute selector. The *| namespace wildcard matches both href and xlink:href:

document.querySelectorAll('use[*|href="#icon-menu"]');

To find the elements that contain those icons, such as the buttons, use closest() on each result, or :has():

document.querySelectorAll('button:has(use[*|href="#icon-menu"])');

Gotcha: icons from an external sprite file

Many sites keep the sprite in its own file:

<svg><use href="/icons.svg#icon-close"/></svg>

Here the original isn't in your document at all, so getUseSource() returns null and document.getElementById('icon-close') finds nothing. The browser loaded /icons.svg as a separate document that scripts can't access. Fetch the file and parse it yourself:

async function getExternalUseSource(use) {
  const url = new URL(use.href.baseVal, document.baseURI);
  const response = await fetch(url);
  const doc = new DOMParser().parseFromString(await response.text(), 'image/svg+xml');

  return doc.getElementById(decodeURIComponent(url.hash.slice(1)));
}

const source = await getExternalUseSource(document.querySelector('use'));

source.querySelectorAll('path');  // the icon's shapes

The browser has already downloaded the file to draw the icon, so the request can often be served from the HTTP cache. Changes to this parsed copy don't affect the page, because it's a separate document.

Gotcha: clicks report the <use>, not the shape

Events from the copies are retargeted to the <use>, like events from any shadow tree. And because the tree is closed, composedPath() doesn't include the shape either. In Chromium 159 and Firefox 159:

document.addEventListener('click', (event) => {
  event.target;          // the <use> element
  event.composedPath();  // [use, svg, button, ..., document, window]
});

document.elementFromPoint(x, y);  // also the <use>

So you can't use a selector such as event.target.closest('.bar') to find out which part of an icon was clicked. If that matters, draw each part with its own <use>, or inline the icon as described below.

Gotcha: your CSS selectors don't reach the copies either

The same boundary applies to stylesheets. Selectors are matched against the original element where it sits in the document, not against the copy's position under the <use>. In both browsers:

use rect { fill: red; }              /* no effect on the copies */
#menu-button rect { fill: red; }     /* no effect on the copies */
#icon-menu rect { fill: red; }       /* styles every copy */

To style one instance differently, set an inherited property on the <use> and have the original use it. currentColor is the common choice:

<symbol id="icon-menu" viewBox="0 0 10 10">
  <rect y="1" width="10" height="2" fill="currentColor"/>
  ...
</symbol>

#menu-button use { color: blue; }  /* the copies inherit it */

CSS custom properties are inherited too, so fill: var(--bar-color) in the original lets you pass more than one colour.

When you need real elements: inline the <use>

If you need to query, animate or listen to the individual shapes of one instance, replace the <use> with a real copy of the original. This function handles icons defined with <symbol> (which become a nested <svg>) and plain elements such as a <g> (which are moved by the <use>'s x and y):

function inlineUse(use) {
  const ns = 'http://www.w3.org/2000/svg';
  const source = getUseSource(use);

  if (!source) {
    return null;
  }

  let copy;

  if (source.localName === 'symbol') {
    copy = document.createElementNS(ns, 'svg');

    for (const name of ['viewBox', 'preserveAspectRatio']) {
      if (source.hasAttribute(name)) {
        copy.setAttribute(name, source.getAttribute(name));
      }
    }

    for (const name of ['x', 'y', 'width', 'height']) {
      if (use.hasAttribute(name)) {
        copy.setAttribute(name, use.getAttribute(name));
      }
    }

    copy.append(...[...source.childNodes].map((node) => node.cloneNode(true)));
  } else {
    const offset = document.createElementNS(ns, 'g');
    offset.setAttribute('transform', `translate(${use.getAttribute('x') || 0} ${use.getAttribute('y') || 0})`);
    offset.append(source.cloneNode(true));

    copy = document.createElementNS(ns, 'g');
    copy.append(offset);
  }

  for (const attr of use.attributes) {
    if (!['href', 'xlink:href', 'x', 'y', 'width', 'height'].includes(attr.name)) {
      copy.setAttribute(attr.name, attr.value);
    }
  }

  for (const el of copy.querySelectorAll('[id]')) {
    el.removeAttribute('id');
  }

  use.replaceWith(copy);

  return copy;
}

inlineUse(document.querySelector('#menu-button use'));

document.querySelectorAll('#menu-button rect').length;  // 3

In my tests in Chromium 159 and Firefox 159, the inlined icon rendered pixel for pixel the same as the <use> for both cases. Two things change, though:

Try it in your browser

The icon below is drawn with <use href="#demo-icon">. Press the first button to run this article's queries against it, then the second to inline it and run them again:

Results will appear here.

Summary