Manipulate SVG using Javascript

Is there a way to edit an SVG file directly in JavaScript without relying on any framework?

I have a master SVG file that contains some child SVG elements.

I've managed to retrieve the content of these children using Ajax, but now I need to insert them into an SVG tag.

For instance, I created a new tag:

var svgInclude = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgInclude.setAttribute('id', 'include_1');
svgInclude.setAttribute('height', widthVis);
svgInclude.setAttribute('width', widthVis);
svg.appendChild(svgInclude);

Now, when I try to insert the XML data retrieved from this function:

function loadXMLDoc(url, cb) {
  var xmlhttp;
  if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
  else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) cb(xmlhttp.responseText);
  };
  xmlhttp.open('GET', url, true);
  xmlhttp.send();
}

Using:

loadXMLDoc(host + '/svg/frame_panto_v2.svg', function(xml) {
  svgInclude.innerSVG(xml);
});

Unfortunately, it doesn't work and throws an error

Uncaught TypeError: Object #<SVGSVGElement> has no method 'innerSVG'
. I also tried using innerHTML but encountered the same issue.

Any suggestions on how to paste a downloaded SVG file into an SVG tag?

Thank you for your assistance.

Answer №1

To accomplish this task, utilize the DOMParser.

var parser = new DOMParser();
var doc = parser.parseFromString(stringWithXMLContent, "image/svg+xml");

This will yield an SVG document, allowing you to access the content through doc.documentElement. Additionally, use importNode and appendChild methods to insert it.

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

Is there a way for my extension to prevent a rickroll from starting before the video even begins?

I'm working on creating a Chrome extension that prevents rick rolls. Here's an overview of my manifest.json file: { "name": "AntiRick", "version": "1.0", "description": "Introduci ...

Command-sending ASP page on Android browser controlling a Windows PC

I'm curious about how I can send commands, such as 1, 2, 3, etc., from a web app (classic ASP/ASP.NET) on my Android web browser to a Windows computer on the same LAN network. I want to create a web page with buttons that can act as an instant messeng ...

Issue with updating Angular list reference when deleting an item

My current task involves implementing a feature that displays selected items from a hierarchical structure on the right side. slice.component.ts : import { Component, Input, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core&a ...

Is it possible to make a call to an endpoint from within the node project?

I'm currently working on a MERN app that dynamically adds meta tags to React pages without using server-side rendering. In order to achieve this, I need to extract the query parameters from the main server file and assign the relevant metadata content ...

Deactivating a form field depending on a selected radio button in Angular 2

If I have two radio buttons, with a click function called localClick for the first button to give value 1 and the second button to give value 2. <div class="ui-g-12"><p-radioButton name="group1" value="Local" (click)=localClick(1) label="Local"&g ...

Trigger a warning pop-up if a selection has not been made in a dropdown menu using jQuery

I am attempting to display an alert popup when the user fails to select a value from the dropdown menu. Below is my HTML code: <div id="reminder" class="popup-layout"> ... ... </form> </div> In my JavaScript function page, I have tried ...

Utilize JavaScript to assign a value to a concealed Pardot field

Recently, I've been working on setting a hidden Pardot field within an iframe. Oddly enough, when I manually input the query selector in my Chrome console, I successfully locate the element. However, when running this code snippet (embedded in the &l ...

How to Use Jquery to Delete a Specific String

I've been attempting to remove certain strings from a string using Jquery, however it seems like the code isn't working and my variable remains unchanged. var classes = $("body").attr('class'); alert('.side-nav' + classes); c ...

Exploring the process of web scraping from dynamic websites using C#

I am attempting to extract data from using HtmlAgilityPack. The website is dynamic in nature, displaying content after the page has fully loaded. Currently, my code retrieves the HTML of the loading bar using this method, but encounters a TargetInvocation ...

Click event not triggered when transitioning to Service section in Thinkster tutorial

I've been following a tutorial on MEAN stack development () and I encountered an issue after incorporating Angular Services. For some reason, the function incrementUpvotes stopped working and I'm struggling to identify the cause. Since I'm r ...

"Create visually appealing designs with Material UI by incorporating round images in Card

Recently delving into full stack development, I've been experimenting with coding to enhance my understanding of frontend using React JS and Material UI. In the process, I incorporated a card component to display posts from the backend. However, I enc ...

The deleteCell function will not properly function when directly targeting selected table rows (trs)

I'm currently facing an issue while trying to dynamically access a specific tr element. Although I believe that the tr is being selected, when attempting to use the deleteCell method, it gives an error stating that the object does not have such a meth ...

Utilizing the power of Vue.js 3 to dynamically apply multiple custom classes to a table

I recently started using Vue for my frontend project and I am facing a challenge. I am trying to dynamically add classes to my table based on user input. Currently, I am able to add only one class, but I want to extend this functionality to work with an ar ...

What are the steps to set up ChartJS on a personal computer?

Currently, I am working on creating charts with ChartJS using the CDN version. However, I would like to have it installed directly on my website. After downloading ChartJS v4.1.1, I realized that it only contains typescript files. Since I cannot use TS fil ...

Is there a way to create a list of languages spoken using Angular?

I am in search of a solution to create a <select> that contains all the language names from around the world. The challenge is, I need this list to be available in multiple languages as well. Currently, I am working with Angular 8 and ngx-translate, ...

Redirect to a new page following a toastr notification in an Angular application

Looking for a way to automatically navigate to another page after a toastr notification disappears. showToasterWarning(){ this.notifyService.showWarning("No Data Found for this Date!", ""); } The notifyService is responsible ...

What is the process of relocating JSON and JS code from within an HTML file to external files?

My goal is to separate JSON and JavaScript code from the HTML file by moving them into external files. The examples shown below were part of a test I conducted to verify that the data was being successfully imported. As I begin to include real data, the J ...

An unusual html element

During a recent exploration of a website's code using the inspect tool, I stumbled upon a tag that was completely unfamiliar to me. <gblockquote></gblockquote> I've come across a blockquote before, but never a gblockquote. Interest ...

What methods do you suggest for storing the app's state in the browser to reduce the number of requests to the backend?

Recently at work, I encountered an issue with our application that is generating unnecessary requests and causing performance issues. Our technology stack consists of Typescript, React, and Redux (not Redux-Toolkit). I am seeking the following outcomes: ...

How can I incorporate a custom color into a preset navbar on an HTML webpage?

<div class="navbar-header"> <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" style="color: blue;" class="navbar-toggle collapsed" type="button"> <i class="fa fa-reo ...