ChatGPT解决这个技术问题 Extra ChatGPT

Add SVG element to existing SVG using DOM

I have a HTML construction that resembles the following code:

<div id='intro'>
<svg>
//draw some svg elements
<svg>
</div>

I want to be able to add some elements to the SVG defined above using javascript and DOM. How would I accomplish that? I was thinking of

var svg1=document.getElementById('intro').getElementsByTagName('svg');
svg1[0].appendChild(element);//element like <line>, <circle>

I am not very familiar with using DOM, or how to create the element to be passed to appendChild so please help me out with this or perhaps show me what other alternatives I have to solve this issue. Thanks a lot.


R
Rvervuurt

If you want to create an HTML element, use document.createElement function. SVG uses namespace, that's why you have to use document.createElementNS function.

var svg = document.getElementsByTagName('svg')[0]; //Get svg element
var newElement = document.createElementNS("http://www.w3.org/2000/svg", 'path'); //Create a path in SVG's namespace
newElement.setAttribute("d","M 0 0 L 10 10"); //Set path's data
newElement.style.stroke = "#000"; //Set stroke colour
newElement.style.strokeWidth = "5px"; //Set stroke width
svg.appendChild(newElement);

This code will produce something like this:

<svg>
 <path d="M 0 0 L 10 10" style="stroke: #000; stroke-width: 5px;" />
</svg>



createElement: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

createElementNS: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS


I get Uncaught TypeError: Cannot read property 'setAttribute' of null.
@Rvervuurt Hey, what are you doing with my post? :D
@m93a Removing unnecessary images. If you want to have fun with images, go to a forum or chat, here it just distracts :)
Why's this not drawing? oh yeah, the namespace: gets me every time.
It should be noted that contrary to what one would think, you most use newElement.setAttribute() to set attribute as oppose to newElement.setAttributeNS() - at least in Chrome.
r
ragingsquirrel3

If you're dealing with svg's a lot using JS, I recommend using d3.js. Include it on your page, and do something like this:

d3.select("#svg1").append("circle");

I would like to do it using plain javascript, without external libraries or functions
I second the suggestion for using D3. If you're just doing a one-off, then yeah, write it in pure JavaScript. But if you do a lot of work with SVG's, then you're doing yourself a huge favor to switch over to d3.js. It's an incredibly lightweight library, too. And it does more than just SVG's; it actually converts the DOM to a database. It's just that it makes working with SVG's a snap, so it has become a de facto SVG library.