Home > OS >  How can I access an SVG element embedded in a CSS `background` from JavaScript?
How can I access an SVG element embedded in a CSS `background` from JavaScript?

Time:09-28

Given this HTML and CSS that embeds an SVG as a background:

<div ></div>

.box {
  width: 300px;
  height: 200px;
  background: url('data:image/svg xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><rect id="rect" width="100" height="100" fill="red"><animate attributeName="x" from="0" to="400" dur="6s" repeatCount="indefinite"/></rect></svg>');
}

I want to use JavaScript to access #rect like so:

// Wait for the SVG to load.
window.onload = function() {
  // ...but this still logs null
  console.log(document.getElementById("rect"));
}

But this prints null in the console. Is there any way to get a reference to this <rect> via JavaScript?

CodePudding user response:

When loaded as a CSS <image> (like through background-image but also through content and other CSS properties), your SVG document is loaded in an external environment, that scripts don't have access to, just like it is in an HTML <img> by the way.

For all that matters you can even forget there is an SVG Document loaded at all here.
If you want to modify the image, you need to edit the URL directly:

const box = document.querySelector(".box");
// rule is a string
const rule = getComputedStyle(box).backgroundImage;
box.style.backgroundImage = rule.replace("red", "blue");
.box {
  width: 300px;
  height: 200px;
  background: url('data:image/svg xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><rect id="rect" width="100" height="100" fill="red"><animate attributeName="x" from="0" to="400" dur="6s" repeatCount="indefinite"/></rect></svg>');
}
<div ></div>

  • Related