Removing an SVG element from the DOM with jQuery

I use jQuery to add an element to the embedded SVG, for example:

var rect = SVG('rect'); $(rect).attr( { x: left, y: top, width: right - left, height: bottom - top, style: style } ); $(parentElement).append(rect); 

parentElement can be, for example, $ ('g: first', svgRoot), where svgRoot refers to an inline SVG element.

 function SVG(elementName) { return document.createElementNS('http://www.w3.org/2000/svg', elementName); } 

This works well, a new rectangle is displayed in the browser and added to the DOM:

screenshot

However, this rectangle is not deleted. It is still displayed in the browser and is present in the DOM:

 $(rect).remove(); 

I also tried

 rect.parentNode.removeChild(rect); 

resulting in the error message "Uncaught TypeError: Unable to call the removeChild method from null".

Do you have any idea how I can fix this? Using jQuery SVG or another plugin / framework in my project is not possible.

+8
javascript jquery html5 svg
source share
2 answers

I decided to solve this problem using group s.

I ended up with this code:

 var group = getGroupByName(name); group.parentNode.removeChild(group); ... function getGroupByName(name) { var container = document.getElementById("container"); var groups = container.getElementsByTagName("g"); for(var i=0; i<groups.length; i++) { if(groups[i].getAttributeNS(null, "name") === name) { return groups[i]; } } return null; } 

Where container is my main SVG element.

This is verified and true. It works correctly.

EDIT

As stated in the comments. You can find this script that works. As in your example. It creates 4 rectangles and removes the first 2.

If you want to remove the first element, you must specify this:

 $("rect").first().remove(); 

Or, if you want to do something with all of your rectangles, you can come close to this with something like:

 $("rect").each(function() { ... //could remove them here } 

Edit 2

According to the last comment, if you have a link to an object, you can use it to delete it.

This updated script will show you that with lastRect you can delete this last rectangle that was added.

+5
source share

I found that executing .find("*") helped a lot, I assume that it smooths the DOM and thus ignores any nesting difficulties that jQuery cannot handle (maybe ... this is at least my theory )

So, for example, this removes everything except the rect, g, svg elements.

$("svg").find("*").not("rect, g").remove();

jSFiddle showing find () and removing svg elements

+1
source share

All Articles