Filtering tags using jQuery
I have the following SVG:
<g>
<rect id="1">
<text id="2">
<g>
<path id="3">
</g>
</g>
<text id="4">
<rect id="5">
Using jQuery I wish to remove all the 'g' tags from the collection, leaving everything else in tact (including the tags within the now stripped 'g' tags).
So, the jQuery collection I require would look like this:
<rect id="1">
<text id="2">
<path id="3">
<text id="4">
<rect id="5">
I've tried using a filter, but to no avail (it doesn't retain the children of the stripped 'g' tags):
$result = $svgCollection.filter('*:not(g)');
I thought filter acted as a recursive function, but it doesn't seem to work. Have also tried:
$result = $svgCollection.filter('text, rec开发者_运维问答t, path');
But no joy. Any ideas?
$('g').each(
$(this).replaceWith($(this).contents())
});
Or shorter:
$('g').replaceWith(function() {
return $(this).contents()
});
Dont know if its a good solution but:
$("g").children().unwrap();
The unwrap() method was designed to achieve exactly what you want:
$svgCollection.find("g > *").unwrap();
EDIT: If you don't want this operation to affect the DOM, you can clone the collection:
var $result = $svgCollection.clone().find("g > *").unwrap().end();
精彩评论