JQuery Remove all but matched rows

I am trying to delete all rows from the EXCEPT table of matching rows:

This code deletes the lines that I actually want to keep -

$("table#traffic").each(function() {
    $("td:contains('" + selected_text + "')").parent().remove();
}); 

      

I basically want to do something opposite of the above.

+2


source to share


6 answers


Try $("td:not(contains('" + selected_text + "'))").parent().remove();



+1


source


At first glance, I'm confused - you are doing the .each () function in every match ("table traffic #"), but then you don't integrate $ (this) anywhere in your .each () which tells me you can exclude the .each () loop entirely.

As for your question, does: not selector with: contains work?



$("td:not(:contains('" + selected_text + "'))").parent().remove();

      

+1


source


The delete function can also take an expression as a parameter.

$("table#traffic tr").remove(":not(:contains('" + selected_text + "')"));

      

Interestingly, the following profiles are somewhat faster with a fairly large number of lines. I decided that calling parent () would consume more time.

$("table#traffic td:not(:contains('" + selected_text + "'))").parent().remove();

      

So, I think you can go with what you better read.

+1


source


there is some function you could work with. http://docs.jquery.com/Traversing/not#expr

0


source


I'm disappointed that the above solutions are not specific to his particular table and actually check all and all the rows of the table. This may not be the desired effect.

$("table#traffic td:not(:contains('" + selected_text + "'))").parent().remove();

      

0


source


I'm surprised nobody mentioned the filter method ... From the docs:

filter (expr)
Removes all elements from the set of matched elements that do not match the specified expression (s). This method is used to narrow the search results ...

So, maybe something like this?

$("table#traffic tr")
    .filter(':has(td:contains('" + selected_text + "'))')
    .remove();

      

Of course, you can use a combination not

to achieve the same choice (there are many other ways to trick this cat). I just thought I would call the function filter

, since that is what it exists for.

Finally, I also want to point out that none of the approaches you've answered so far describe a very likely situation where you end up deleting lines you don't want! For example, if a line contains multiple cells, you don't want just one of those cells in the line, not containing your text, to cause the entire line to be deleted! Note that in my solution above, filtering is done at the row level, not at the cell level. (I haven't tested this, so please don't jump on me if it doesn't work exactly the same way!)

Good luck!
-Mike

0


source







All Articles