jQuery - Select everything except a single elements and its children?

后端 未结 6 1616
栀梦
栀梦 2020-12-10 03:47

I\'m trying to remove everything in the whole body, except of a single element and its children. How can I accomplish this?

Edit 1 Consider the foll

相关标签:
6条回答
  • 2020-12-10 03:52
     $("body > *").not("body > #elementtokeep").remove();
    

    You can replace the not() part with whatever you want to keep

    0 讨论(0)
  • 2020-12-10 03:58

    You can do it like this:

    $('body > *:not(#dondelete)').remove();
    

    Where your element has id="dondelete" and is a child of body.

    0 讨论(0)
  • 2020-12-10 04:04

    This code worked for me.

    $('body > * :not(#123)').remove()
    

    You need to give space between * and : . Earlier when try to use the code with

    $('body > *:not(#123)').remove() it did not work. I had to give space between * and : character.

    Happy coding.

    0 讨论(0)
  • 2020-12-10 04:09

    Try

    $('body > *:not(#123)').remove()
    

    http://api.jquery.com/not-selector/

    0 讨论(0)
  • 2020-12-10 04:10

    This is an old question, but the accepted answer is wrong. It doesn't work in this situation (see http://jsfiddle.net/LVb3V/ ) and certainly not as a general solution.

    Better to use:

    $('body *').not('#div2, #div2 *').remove()​;

    This will remove all elements in the body except for div2 and all the elements it contains.

    0 讨论(0)
  • 2020-12-10 04:15

    I think that

    $("body *").not("body #div2")
               .not("body #div2 #elementtokeep")
               .not("body #div2 #elementtokeep *")
               .remove();
    

    is the easiest way to focus it.

    http://jsfiddle.net/6vb2va6g/

    0 讨论(0)
提交回复
热议问题