Creating dynamic visuals using SVG with <symbol> tag

I am attempting to generate an SVG element using JavaScript and then append it to the DOM. The SVG element makes reference to a symbol. I have found success using the insertAdjacentHTML method, but I am struggling to achieve the same result with the appendChild method.

Even though all the necessary elements appear to be in the DOM when using appendChild, the rendering is incorrect. Can anyone help me troubleshoot this issue?

http://codepen.io/bradjohnwoods/pen/dGpqMb?editors=101

<svg display="none">
  <symbol id="symbol--circle--ripple" viewBox="0 0 100 100">
    <circle cx="50" cy="50" r="25" />
  </symbol>
</svg>

<button id="btn">
</button>

<script>
var btn = document.getElementById('btn');

//var myString = '<svg><use xlink:href="#symbol--circle--ripple" width="100" height="100" class="btn--ripple__circle"></use></svg>';
//btn.insertAdjacentHTML('afterbegin', myString);

var svg = document.createElement('svg');
var use = document.createElement('use');
use.setAttribute("xlink:href", "#symbol--circle--ripple");
use.setAttribute("width", "100");
use.setAttribute("height", "100");
use.classList.add("btn--ripple__circle");

svg.appendChild(use);
btn.appendChild(svg);
</script>

Answer №1

If you try to create SVG elements using createElement, it won't work. You have to use createElementNS to create them in the SVG namespace

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use');

insertAdjacentHTML calls the html parser which automatically takes care of the element namespaces.

Similarly, using setAttribute to create attributes in the xlink namespace, like xlink:href, won't work. Instead, you should use

setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#symbol--circle--ripple");

and that's the way to do it

Answer №2

After some searching, I discovered that utilizing .createElementNS and .setAttributeNS was the key to solving the issue.

var svgElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
var useElement = document.createElementNS('http://www.w3.org/2000/svg', 'use');
useElement.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#symbol--circle--ripple');

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

web browser editing tool

Do you know which library was utilized to create this JSON editor? https://i.sstatic.net/kGpGz.png You can find it at . The editor efficiently checks the syntax and shows errors when necessary. ...

Instructions for implementing a Back button that takes you directly to the text or link you clicked on to view an image

My goal is to have multiple anchor links within text, each linking to a specific image on the same page. Once the user views the image, I want them to be able to click a 'Back' button that will take them back to where they left off in the text. ...

What exactly does the next() function do in NodeJS/SailsJS?

I recently came across a SailsJS tutorial where the next(); function was used for user authentication. However, I'm still unsure of its exact purpose. Can anyone provide clarification on this? ...

Launching event handlers and applying CSS classes within a single scenario

How can I toggle the visibility of a button based on form field validation in JavaScript? I want to show or hide the button when the .confirm button is clicked, and if the form is valid, add a checkmark to the body element through event listener. The issu ...

Utilizing jQuery ajax to dynamically update map markers on Google Maps at intervals

I am currently working on a project that involves updating a Google map with a marker at regular intervals. I have an Ajax request that retrieves a single latitude and longitude coordinate, but I'm struggling to display it on the map. One option coul ...

Getting the ng-model value from a Directive's template and passing it to a different HTML file

When working with my name directive, I am unable to retrieve the value of ng-model from the template-url. team-two.html <form name="userForm" novalidate> <div name-directive></div> </form> <pre>{{userForm.firstname}}< ...

What is the process by which React recreates the React element tree (virtual DOM) with every state update?

From what I've gathered, every time a state is updated in React, it generates the react element tree (virtual DOM) and then compares it with the new one using a diffing algorithm. However, there's something I find puzzling. Let's say we hav ...

The Material UI appbar fails to resize properly on mobile devices

I have added a material-ui appbar to the top of my website. Check it out here: Website Appbar However, when I resize the website to mobile size, the appbar does not adjust responsively to the screen. Here's how it looks on mobile: Appbar when in mobi ...

The parent's height dynamically adjusts based on the height of its visible children using only CSS

I am dealing with the following structure: <div class="body"> <div class="wrapper"> <div class="dialog"> <div class="content-0"></div> <div class="content-1&quo ...

Using React with TypeScript to ensure that at least one key of a type is not null, even if all keys are optional

Within my Typescript code, I have defined an event type that includes various time parameters: export type EventRecord = { name: string; eta: string | null; assumed_time: string | null; indicated_time: string | null; }; I also have a func ...

Using setTimeout() in JavaScript to create a delay between functions

Is there a way to add a delay between the execution of each function in my program? Currently, I have the following setup: function function0() { setTimeout(function1, 3000); setTimeout(function2, 3000); setTimeout(function0, 3000); } While t ...

Using Vue.js to send a slot to a child component in a nested structure

Check out this interesting modal component configuration //modal setup <template> <slot></slot> <slot name='buttons'></slot> </template> Imagine using it like a wizard //wizard setup <template> ...

What causes the initial network call to be slower than all the following ones?

Can someone help me understand why the first network call takes more than double the time of subsequent ones, even though DNS resolving should not take more than 5-50ms and only happens in the initial call? I conducted tests with famous URLs in separate in ...

Tips on positioning content beneath a fixed header or navigation bar when viewed in a web browser

Hi, I'm having an issue with creating a fixed header using HTML and CSS. When I set my header to be in a fixed position, it covers up the content below it. I want the content to be positioned under the header when the page is loaded. Additionally, I&a ...

What is the best way to remove a property from an object in React if the key's value is set to false?

I'm currently working on a form component and I've encountered an issue. Whenever I submit the form, it returns an object with various fields such as email, fieldName1, fieldName2, first_name, last_name, and organization. Some of these fields are ...

How can you efficiently update another ng-model value based on a select input in AngularJS using ng-change?

<select data-ng-init="selectedItem='previewWidth = 1920; previewHeight = 1080'" data-ng-model="selectedItem" data-ng-change="GetNewData(); {{selectedItem}}"> <option value="previewWidth = 1920; previe ...

Unidentified variable in Angular Ajax function when accessed outside its scope

Currently, I am in the process of creating a ticket admin table. However, I am facing some challenges with exporting a variable outside of an ajax function. Here is my code: app.controller('bodyController',function($scope,$http,$sce){ $scope.ti ...

Is it more efficient to pass session variables through an ajax function, or should I access them directly within the script?

I am currently working on a page that utilizes an ajax function to retrieve updates from another page. The function requires the user's id, which is obtained from a session variable, to fetch any new updates. These updates are then displayed in a spec ...

What is the method to activate map dragging in Leaflet only while the spacebar is pressed?

When using Leaflet maps, the default behavior is to drag the view around by only clicking the mouse. However, I am interested in enabling dragging with the mouse only if the spacebar is pressed as well. I would like to reserve mouse dragging without the sp ...

Prevent Float Filtering in AngularJS

As I work on creating a directive in AngularJs, I am facing an issue. The directive is supposed to receive a JSON object from the app controller and display its content accordingly. To better illustrate my problem, I have created a simple demo which can b ...