skip to Main Content

I have an SVG sprite with all my icons, and when dinamically adding an icon in Javascript I use thise code:

let closeButton = document.createElementNS("http://www.w3.org/2000/svg", "svg");
let svgUse = document.createElementNS('http://www.w3.org/2000/svg', 'use');
svgUse.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'css/sprite.svg#warning');
closeButton.append(svgUse);

I think can understand straight by looking at the code what I am asking.

The above code works just fine, but according to MDN docs on xlink:href:

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

So in order to be ready for the future, how would I dynamically set the href attribute of the use element?

I know that you can’t just set it with setAttribute function. But what would I put in the namespace parameter for it to work?

    svgImg.setAttributeNS('what to put here?', 'href', 'css/sprite.svg#warning');

I couldn’t find any documentation anywhere about this.

2

Answers


  1. A value of null is fine, but you can also use the non-name-spaced setAttribute() method.

    const uses = document.querySelectorAll("use");
    uses[0].setAttributeNS(null, "href", "#target");
    uses[1].setAttribute("href", "#target");
    <svg>
      <defs>
        <rect id="target" width="30" height="30" fill="green"/>
      </defs>
      <use/>
      <use x="40"/>
    </svg>
    Login or Signup to reply.
  2. Wrap you code in a single native Web Component so you have one place to make changes.

    customElements.define("svg-icon", class extends HTMLElement{
      connectedCallback(){
        let is = this.getAttribute("is");
        this.innerHTML = `<svg viewBox="0 0 48 48"><use href="#${is}"/></svg>`
      }
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search