5

I would like to select the last path in an SVG and remove it. I've tried a variety of methods, in pure javascript and in jquery and I don't seem to be able to access the SVG properly or its paths.

HTML:

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

I CAN clear the SVG using:

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

I CAN see the SVG's contents using:

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

However, I CANNOT similarly select the SVG and see it's path contents...

my goal is something like

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

thanks a million for any help

2
  • Can you jsfiddle.net an example? Commented Sep 22, 2011 at 23:53
  • See my comment below. Selecting the last path was actually quite easy using jquery, pure javascript probably would have worked too. there were other problems in my code. Thanks. Commented Sep 24, 2011 at 22:49

2 Answers 2

7

Here's executable code in pure JavaScript:

var paths = svgDoc.getElementsByTagName("path");
var last_path = paths[paths.length - 1];
last_path.parentNode.removeChild(last_path);
Sign up to request clarification or add additional context in comments.

1 Comment

Turns out that selecting the last path wasn't actually what was holding me back... fixed something else and it worked. this solution looks decent tho. i'm using some jquery now and this was good enough: var svg = document.createElementNS(ns, 'svg'); $('svg path:last-child').remove();
2

I'm assuming that you're using an SVG compatible browser, such as Firefox.

It's been a while since I tried to manipulate SVG via jQuery. I remember that I was reluctant to use an SVG jQuery plugin, but without one I was having some problems accessing the elements in the DOM. Including the jQuery SVG plugin allowed me to access the elements so including it might help with the problems that you're having.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.