Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 440
No_name Avatar asked Aug 17 '12 05:08

No_name


People also ask

How to remove all option in select using jQuery?

Then, we remove all the selected options using the remove() method. We use the end() method to revert the selection back to the select box. To add one option, the append() method can be used.

How do I delete everything in a div?

To clear the contents of a div element, set the element's textContent property to an empty string, e.g. div. textContent = '' . Setting textContent on the element removes all of its children and replaces them with a single text node of the provided value.

How to use toggle jQuery?

jQuery toggle() Methodshow() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: This method can also be used to toggle between custom functions.


2 Answers

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

like image 171
Alex Kalicki Avatar answered Oct 06 '22 00:10

Alex Kalicki


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);
});​
like image 35
Shih-En Chou Avatar answered Oct 06 '22 02:10

Shih-En Chou