No_name
No_name

Reputation: 2810

Jquery remove everything except for bolded

I have html like this:

<div id="divTestArea1">
    <b>Bold text</b>
    <i>Italic text</i>
    <div id="divTestArea2">
            <b>Bold text 2</b>
            <i>Italic text 2</i>
            <div>
                    <b>Bold text 3</b>
            </div>
    </div>

and I would like to remove all elements that aren't bold. I've tried with this code:

$('*:not(b)').remove();

and a couple other variations but they all either error out or remove everything. btw, are jquery selectors and jsoup selectors 100% compatible? I'd like to use the answer to this in jsoup as well.

Upvotes: 5

Views: 287

Answers (5)

Shih-En Chou
Shih-En Chou

Reputation: 4185

My solution:

I clone <b> and save it into memory. ->Remove all -> insert <b> into <body>

here is my code: http://jsfiddle.net/sechou/43ENq/

$(function(){
   var tmpB = $("b").clone();
   $('body').remove();
   $("body").append(tmpB);
});​

Upvotes: 3

Alexander
Alexander

Reputation: 23537

I prefer .detach().

var $body = $("body");
var $b = $("b", $body).detach();
$(":not(b)", $body).remove();​​​​​​​​​​​
$body.append($b);

This way you don't need to either move or clone anything to overcome the problem of the deletion of the objects wrapping your <b/> elements.

(demo)

Upvotes: 2

adeneo
adeneo

Reputation: 318312

Move all elements in #divTestArea2 as it is a div and will be removed as well to #divTestArea1, then filter out anything that is'nt a <b> and remove it :

$("#divTestArea1").append($("*", "#divTestArea2")).find('*').filter(function() {
    return this.tagName !== 'B';
}).remove();

FIDDLE

The above keeps the #divTestArea1 element intact, to remove everything but the <b> elements, something like :

$('body')​.append($('b'))​.find('*')​.not('b')​.remove();​

FIDDLE

Upvotes: 2

codef0rmer
codef0rmer

Reputation: 10530

Try this:

// Find all the <b> tags and unwrap them so they all become siblings and finally 
// remove non <b> siblings
$('body').find('b').unwrap().siblings('*:not(b)').remove();

Demo: http://jsfiddle.net/3f2Hu/

Upvotes: 1

Alex Kalicki
Alex Kalicki

Reputation: 1533

Your current code removes the document <body> as well as all <div>s which contain the <b> tags. If you only want to save the bold text then Shih-En Chou's solution works well. If you want to save the <div> structure that the <b> tags are in as well you could do this:

$("body *:not(div, b)")​​​​.remove();​

DEMO

Upvotes: 5

Related Questions