Using SVG within a string is successful, however, incorporating it as an element is not functioning

My goal is to save SVG icons as <symbol> markup in localStorage and then inject them after the DOMContentLoaded event.

Initially, I planned to utilize document.createElement('svg') and insert the element before the first node in document.body.

However, it seems that in Chrome (and possibly other browsers), the icon does not display unless I set the innerHTML of a div with the string representation of the <svg> element, and then insert the div into the document.

Below is a simplified example:

var sprites = document.getElementById('sprites');

var circles = [
  '<symbol id="circle-yellow"><circle cx="25" cy="25" r="20" fill="yellow" /></symbol>',
  '<symbol id="circle-blue"><circle cx="25" cy="25" r="20" fill="blue" /></symbol>'
];

// Insert the yellow circle symbol by creating an SVG element.
var yellowDiv = document.createElement('div');
var yellow = document.createElement('svg');
yellow.innerHTML = circles[0];
yellowDiv.appendChild(yellow);
sprites.appendChild(yellowDiv);

// Insert the blue circle symbol by inserting the SVG string.
var blueDiv = document.createElement('div');
blueDiv.innerHTML = '<svg>' + circles[1] + '</svg>';
sprites.appendChild(blueDiv);
#sprites {
  dispay: none;
}

svg {
  border: 2px solid black;
}
<svg height="50" width="50"><use href="#circle-yellow"></use></svg>

<svg height="50" width="50"><use href="#circle-blue"></use></svg>

<!-- Will hold <svg> elements referred to by <use> elements. -->
<div id="sprites"></div>

Why is the yellow circle not visible?

I have a suspicion that it may be related to the <svg> element for the yellow circle not displaying as a 150x300 box at the bottom of the page. This is puzzling because both <svg> elements are children of a div with display: none, so neither should be visible.

Answer №1

When examining

document.createElement('svg').constructor
, it becomes evident that it is actually generated as an HTMLUnknownElement:

> document.createElement('svg').constructor;
< ƒ HTMLUnknownElement() { [native code] }

The reason for this is that SVG is not a part of HTML and needs to be namespaced in order to function properly. You can achieve this by using the following code:

document.createElementNS("http://www.w3.org/2000/svg", "svg");

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

Import JSON data entries into the agenda of a React Native calendar

I am encountering difficulties loading JSON Data into my Calendar Agenda. Unfortunately, there is limited documentation available on the process of loading JSON into Agenda items by date comparison. If anyone could provide assistance, it would be greatly a ...

Retrieve data from JSON fields within the message body

One question I have regarding the implementation in my Controller class involves the following line: this.template.convertAndSend("/topic/greetings", message); The 'message' being sent is an arrayList. In a JSP file, I establish a sock ...

Store the result of an EJS include tag in a JavaScript variable

I have my footer HTML contained in the file named footer.ejs. I am looking to add this HTML dynamically to another page using JavaScript. The following code snippet does not seem to be functioning properly. Is there a way to store a template output in a J ...

Retrieve information from Google Sheets to use in SVG map

While working on a local HTML page, I encountered an issue with my script. I am using the svgMap library to create a map of movies I have seen, pulling data from a Google Sheets document using the opensheet library. The JSON output looks like this: [{"Coun ...

When triggered by a click, the function gradually fades in and out. It superimposes one image on top of another, but unfortunately, the sizes

Due to different screen sizes, the image does not appear on top of another image exactly. It seems like a new function is needed. One that does not overlap with another image (by clicking the function for a few seconds), but rather replaces it for those fe ...

Is it practical to extract the page type/name from the CSS of the selected tab?

My website has multiple tabs on a single page and I want to integrate Google Analytics code. However, since all the tabs are part of the same page, I need a way to track which tab the user is interacting with. Would using CSS to check for the selected tab ...

Deleting lines from JSON object using Angular or JavaScript

On my webpage, I have a list where you can add a new line by pressing the "+" button (easy with push), but I'm not sure how to remove lines using the "X" button. https://i.stack.imgur.com/nm06A.png This is the JSON structure: "priceExtra" : [ ...

Utilize Node JS to assign variables to HTML form inputs

Can anyone help me with storing HTML form inputs in variables using Node JS? I'm having trouble getting it to work properly. Below is the HTML form snippet: <form action="localhost:8080/api/aa" method="post"> <input id="host" type="text ...

Tips for resolving a double click issue with a jQuery slide up/down animation

When I click a button, there is an animation that makes a div slide up and then down again. It functions the way I want it to, but the first time you click it, it doesn't work; you have to click twice for it to respond. Someone recommended using... ...

Is there a way to automatically scroll through a webpage?

I am looking to have a gif displayed on my website upon loading, and once the animation finishes I want the page to automatically scroll up without requiring any button clicks, revealing my main site. It is important that the gif loads automatically ever ...

Gain a comprehensive understanding of the JavaScript syntax utilized throughout the code

I stumbled upon this JavaScript code that enables asynchronous file uploads, but there are certain parts of it that I'm struggling to grasp. Any insights or explanations would be greatly appreciated - many thanks in advance. // Utilizing Ajax for Fil ...

Assign values from an array in jQuery to a <span> element

I am working with the following HTML code: <input type='radio' class='at-radio' name='re_widget[0][set_style_for_widget]' value='topbanner' /> <span class='at-radio-label'>topbanner</span> ...

Rails : CSS/JavaScript functioning perfectly on local server, facing issues on Heroku deployment

My Rails website features various CSS animation effects and JavaScript elements. While these transitions function smoothly on my local environment, they do not work properly on Heroku. Examining the Heroku logs: 2013-09-17T17:13:36.081145+00:00 app[web.1 ...

Building a solid foundation for web applications involves organizing angularjs components such as controllers, services, and more into

Just starting out with Foundation for Apps, I encountered an issue when trying to organize my angular controllers in a separate folder and use them. In the js folder of my assets directory, I currently have this structure: js/ app.js //contains all co ...

Playing Sound Instantly in JavaScript without delay

I have successfully implemented playing sound with keys using HTML and .play. However, there is a delay as it waits for the track to finish playing before allowing me to play it again instantly upon each click. I am seeking a solution to trigger the sound ...

Disable the parent CSS styling when focusing on the child button

Within an anchor tag, I have a div element. The CSS on the :active state is set to transform the element, but I want to avoid this behavior when focusing on the child element bx--overflow-menu. I am working with NextJS using styled-jsx and SaSS. Here is my ...

Is there a chart tool that allows for editing graphs by simply dragging points?

Currently, I am in search of a charting library that is preferably JavaScript-based (although Flash could work as well) and has the capability to display time series data as a line chart. Additionally, I need this library to allow users to drag points on t ...

Encountering a Type Error in Postman: Unable to destructure

Encountering an issue while using Postman to send a POST request to my backend, resulting in TypeError: Cannot destructure property 'fullName' of 'req.body' as it is undefined The middleware is defined in app.js app.js: import express ...

Retrieve the HTML value of an element in Vue.js by clicking on its adjacent element

Hey there, I'm currently working on a simple notes app and I've hit a roadblock with one particular feature. In my project, I have a card element with a delete button as a child. What I need to achieve is to check if the value of the .card-title ...

What is the procedure for collapsing a table row or grid?

Looking at this image, I'm trying to find a way to collapse the breakfast row. Any ideas on how I can collapse either the entire tr or with a div? ...