Steve
Steve

Reputation: 3663

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, rect, path');

But no joy. Any ideas?

Upvotes: 3

Views: 341

Answers (3)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263067

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();

Upvotes: 0

Eric
Eric

Reputation: 97641

$('g').each(
    $(this).replaceWith($(this).contents())
});

Or shorter:

$('g').replaceWith(function() {
    return $(this).contents()
});

Upvotes: 1

voigtan
voigtan

Reputation: 9031

Dont know if its a good solution but:

$("g").children().unwrap();

Upvotes: 0

Related Questions