Search code examples
jqueryclassremoveallremove-if

How do I remove all elements except one in jQuery?


I'm using jQuery 1.12. After clicking on a TD, I want to remove all elements within it except the one with class "savedBlock", so I tried

$(elt).closest('td').find('.savedBlock').show()
$(elt).closest('td').not('.savedBlock').remove() 

Unfortunately this is having the effect of removing everything . At least everything disappears from the table cell after I run this. If I comment out the $(elt).closest('td').not('.savedBlock').remove() line, nothing is removed but now I see more than what I want. Any suggestions?


Solution

  • Try this one:

    $('td').on('click', function(e) {
        $(this).children().not(".savedBlock").remove();
    })