4

I try to empty() a div but exclude a specific selector.

What I've tried so far:

$('.modal').find('.close').nextAll().empty();
$('.modal').find(':not(.close)').empty();
$('.modal').not('.close').empty();
$('.modal:not(.close)').empty();

HTML:

<div class="modal">
  <a href="#" class="close">Close</a>
  ...I've the need to be removed...
</div>
Tunaki
  • 132,869
  • 46
  • 340
  • 423
yckart
  • 32,460
  • 9
  • 122
  • 129

4 Answers4

7

Could be done like this:

http://fiddle.jshell.net/KLh4E/11/

$(".modal").contents().filter(function(){
    return !$(this).is('.close');
}).remove();
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • @ErickAstoOblitas I'm really not sure how link is related to question? – A. Wolff Jun 10 '15 at 23:37
  • @yckart If your '...I've the need to be removed...' were a set of defined elements like input, span, etc You can use `$('input', $('.modal')).remove()`, `$('span', $('.modal')).remove()` – Erick Asto Oblitas Jun 10 '15 at 23:43
3

I'm not sure about a bug, but the easiest way I could see to accomplish this is:

var el = $('.close');
$('.modal').empty().append(el);

JS Fiddle demo.

A slightly better approach (on the incorrect assumption of multiple .close elements):

$('.modal').each(
  function(){
    var that = $(this),
        el = that.find('.close');
    that.empty().append(el)
  });

JS Fiddle demo.

A combination of using jQuery each() and a plain-JavaScript function:

function fratricide(el) {
  while (el.previousSibling) {
    el.parentNode.removeChild(el.previousSibling);
  }
  while (el.nextSibling) {
    el.parentNode.removeChild(el.nextSibling);
  }
}

$('.close').each(

function() {
  fratricide(this);
});

JS Fiddle demo.

And a JS Perf comparison of approaches. Unsurprisingly the use of plain-JavaScript speeds things up appreciably, even though it is, I think, pretty ugly to read (though I'm unsure how much prettier it could realistically become).

Interestingly (to me, anyway, now that I've updated the previously-linked JS Perf) using a variable to store the reference to el.parentNode makes negligible difference, presumably because despite saving a reference to the element/node the DOM is still having to be accessed in order to find the el.previousSibling node?

David Thomas
  • 249,100
  • 51
  • 377
  • 410
0

You can try this one: http://fiddle.jshell.net/KLh4E/3/

var div = $('.modal').clone().find('a');
$('.modal').empty().html(div);
Jai
  • 74,255
  • 12
  • 74
  • 103
0

jQuery doesn't match textnodes. The text in your example isn't seen as a node contained within .modal; as such it cannot be removed through "selecting all nodes except some other node". Wrapping the text in a simple <span> will do the trick.

ilias
  • 511
  • 4
  • 7