Is there a way to retrieve an SVG element embedded within a CSS `background` using JavaScript?

Here is some sample HTML and CSS that includes an SVG as a background:

<div class="box"></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 am attempting to use JavaScript to target the element with #rect like this:

// Ensure the SVG has loaded.
window.onload = function() {
  // ...however, this still returns null
  console.log(document.getElementById("rect"));
}

Despite my efforts, the console displays null. Is there a different method to reference this <rect> using JavaScript?

Answer №1

When your SVG document is loaded as a CSS <image> (such as through properties like background-image or content), it exists in an external environment where scripts cannot access it, similar to how it functions when loaded as an HTML <img>.

In essence, you can essentially disregard the fact that there is an SVG Document loaded here.

If you wish to make changes to the image, you will need to directly edit the URL:

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 class="box"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for transitioning from custom CSS to Material UI's CSS in JS

I came across a project where someone implemented components with custom CSS. One interesting thing I noticed was a wrapper component, similar to Material UI's Container or just a simple div with applied styles. export const Container = styled.div` ...

There is a syntax error that occurs when attempting to begin a key with a hyphen (-)

Upon initializing the following object, an error is thrown. var postData ={ file_path : "https://s3-us-west-2.amazonaws.com/ps/eams/6-48K.mxf", template_type : "1", template_name : "Basic Tests", job_type : "0", user_note : "my job", access-ke ...

Strange occurrence with getBoundingClientRect() function and F5 refresh, what could be causing this odd behavior?

Apologies for the lengthy code, I have stripped it down multiple times to make it stand-alone. Codepen won't be helpful in this case. You can simply copy and paste the code into an HTML file to see how it behaves. <!DOCTYPE html> <html> &l ...

Tips for utilizing console log within a react form component

I'm currently exploring ways to communicate with a React form in order to provide it with an object.id for updating purposes. While I can successfully console log the object.id within the update button and modal, I am struggling to confirm if the val ...

What is the method for transferring the chosen value from a select element into a textarea?

I am currently working on a feature to allow users to select a color of a shirt from a dropdown menu and have it added to a textarea when they click a button. If anyone has advice on how to achieve the same functionality with a group of radio buttons, it ...

Error: Cannot read property 'X' of undefined in JavaScript when using Django framework

Using p5.js, I am creating drawings with data from a JSON provided by my Django backend. The draw function is defined at the base level of my HTML document within the script element: function draw(json) { if (json["leaf_text"]) { stroke(100) el ...

Even with the use of Display Flex, the menu and text remain misaligned

Hey there! I've been working on recreating a website to improve my skills, and I'm currently focused on replicating the navigation bar of this site: I'm facing an issue with aligning the left line in the nav bar. Instead of being on the sam ...

CSS auto width not applied to images causing a lack of scaling

I recently added this code to my webpage: image { margin: 0 2px 0 0; height: 100px; width: auto !important; overflow: hidden; text-align: center; } The goal was to scale all images to a maximum height of 100px and have the browser adj ...

Discover the most concise string within the array

Is there a way to determine the shortest string in a JavaScript array regardless of the number of elements it contains? I attempted using var min = Math.min(arr[0].length,arr[1].length,arr[2].length); to find the shortest string among 3 elements in an ar ...

React Native tutorial: Changing button color on press

When a user clicks on the TouchableOpacity element, I want to change the color of the button from the default gray to blue. Initially, the 'checked={this.state.newProjects}' newProjects variable is not present in the state, so when clicked it sho ...

Address properties that are undefined before they cause an error

Is there a smart way to manage undefined properties and/or identifiers on an object before they result in failure/returning undefined? Can we intercept access to a non-defined property and address it without resorting to try/catch blocks? var myObj = { ...

The Python error message, "JSONDecodeError: Expecting value: line 1 column 1 (char 0)," indicates that there

What is causing this error to occur? Are there any alternative methods available for converting it into a json file? import requests import json url = 'https://finance.yahoo.com/quote/AMZN/balance-sheet?p=AMZN&.tsrc=fin-srch' r = requests. ...

Changing the state within a slice by utilizing an object as the payload

Here is the code snippet for a standard boilerplate slice: import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { IAuthState } from '../../types'; const initialState: IAuthState = { isAuthenticated: false, profile: ...

Issue with React component not reflecting updated state following Axios call

I have a series of chained axios calls to different APIs. When I log the state inside the function, I see that it is being updated correctly. However, when I log the state in the render() method, I do not see the updated state. The function is triggered a ...

What is the best way to utilize useRef on a component that is not accessible within React BigCalendar?

I'm currently working with React Big Calendar (https://github.com/intljusticemission/react-big-calendar) and facing a challenge with responsive styling. I need to detach the horizontal scrollbar (overflow-x) of a specific div, .rbc-agenda-view, and at ...

What is the best way to use canvas to precisely draw a line on the display at specific absolute coordinates?

As a newcomer to working with canvas and SVG, I am trying to create a line between two specific coordinates. For example, if I have two rectangles, I need to draw a line connecting their centers: https://i.sstatic.net/Rc6qA.png Here is what I have tried ...

Retrieve the Smallest Value from an Array of Objects in a JSON document

My data.json contains information about travel deals. I am looking for the minimum cost when arriving in Amsterdam and departing from London. Could someone guide me on how to properly map through this data? { "currency":"EUR", "d ...

The Datetimepicker component outputs the date in datetime format rather than a timestamp

Currently, I am utilizing the datetimepicker JavaScript script with specific implemented logic: <script> var today = new Date(); var dd = today.getDate(); var mm = today.getMonth(); var yy = today.getF ...

Angular 2 encountering troublesome JSON response with invalid characters

After fetching a JSON response from an external API, I noticed that one of the variable names starts with a # character, making it look like #text in the JSON structure. Unfortunately, Angular doesn't recognize this variable. Is there a way to remove ...

What is the best way to show the associated ul tag?

I've constructed the following HTML: <input id="<code generated id>" type="text" value="select"/> <div id="<code generated id>" class="popup"> <ul id="<code generated id>" class="none"> <li>A</li& ...