简体   繁体   中英

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.

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

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);
});​

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

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)

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM