Home > OS >  SVG JavaScript, how to find out if <use> reference exists
SVG JavaScript, how to find out if <use> reference exists

Time:08-17

I have an SVG file like this

<svg  viewBox="0 0 16 16">
  <use href="assets/icons.svg#my-fancy-icon"></use>
</svg>

Using JavaScript, how do I find out if the href attribute of use element points to an element that actually exists?

CodePudding user response:

Get the <use> element's boundaries: width & height: 0 = not existent

Whenever a svg element is referenced by an <use> element via a href attribute
(or the still widely used legacy syntax: xlink:href)
and it can be successfully appended to the svg's shadow DOM, it will return a width and height value > 0.

If not – getBBox() will return a width and height value of 0.
The use reference is not valid/existent.

let useEls = document.querySelectorAll('use');

useEls.forEach(function(use) {
  let bb = use.getBBox();
  let [width, height] = [bb.width, bb.height];
  if (width == 0 && height == 0) {
    use.closest('svg').classList.add('notavailable')
  }
})
svg {
  height: 10em;
  border: 1px solid #ccc;
  display: inline-block;
}

.notavailable {
  border: 1px solid red;
}
<svg id="svgIcons"  viewBox="0 0 100 100" style="position:absolute; height:0; width:0;" xmlns="http://www.w3.org/2000/svg">
  <symbol id="home" viewBox="0 0 34 48">
    <path d="M33.16,28.12h-5.2v13h-3.44v-16.72l-7.72-8.72l-7.72,8.72v16.72h-3.44v-13h-5.24l16.4-17.4Z" />
  </symbol>
</svg>

<svg viewBox="0 0 34 48">
  <use href="#home" />
</svg>
<svg viewBox="0 0 34 48">
  <use href="#notExistent" />
</svg>

CodePudding user response:

Try this way:

const icon = document.querySelector(".use");

if (icon.firstElementChild === "USE") //...do something
  • Related