Choosing SVG Elements and Paths Using JavaScript

I would like to select the last path in SVG and delete it. I tried various methods, in pure javascript and in jquery, and I seem to be unable to access the SVG correctly or its path.

HTML:

<div id="thesvgwrapper"> <svg id="thesvg"...><path ....></path><path ...></svg> </div> 

I can clear SVG using:

 $('svg#thesvg').empty(); 

I can see the contents of SVG using:

 var svgwrapper = $('#svgwrapper'); var svgcontents = $(svgwrapper).html(); alert(svgcontents); 

However, I CANNOT WATCH to select SVG and see its path contents ...

my goal is something like

 $('#thesvg path:last').remove(); 

thanks a million for any help

+4
source share
2 answers

Here's the executable code in pure JavaScript:

 var paths = svgDoc.getElementsByTagName("path"); var last_path = paths[paths.length - 1]; last_path.parentNode.removeChild(last_path); 
+6
source

I assume you are using an SVG compatible browser like Firefox.

Some time has passed since I tried to manipulate SVG through jQuery. I remember that I did not want to use the jQuery SVG plugin, but without it I had problems accessing elements in the DOM. Turning on the jQuery SVG plugin allowed me to access the elements, so turning it on can help solve the problems you have.

+2
source

All Articles