简体   繁体   中英

Remove all the 'tr' if the any of the 'td' does not have given text

I have a table with many rows . first row is the header.

i want to delete all the rows if any of its td does not have given text.

<tr>
     <td id="1" class="links">Madia</td>
     <td id="" class="edit_client" >Press</td>
</tr>
<tr>
    <td id="2" class="td_link" >Nagara </td>
    <td class="td_link" id="11" class="edit_client">KR Pura</td>
</tr>

I want to delete all the tr , if any of its td does not have given text say "me hussy".

 $('tr').each(function () { 

 });

i do not want delete first row because its header. so function should check from second row onwards.

Try doing this

$('table tr:gt(0)').each(function() {
   if ($('td:contains("me hussy")', this).length == 0) $(this).remove();
});​

Demo on jsFiddle.net

EDIT:

Thanks mesiesta for :gt(0)

EDIT

With respect to OP's comment

var name = "me hussy";
$('table tr:gt(0)').each(function() {
   if ($('td:contains("'+ name +'")', this).length == 0) $(this).remove();
});​
var name="me hussy";
$('tr').not(':first').not($('tr').find('td:contains('+name+')').parent()).remove()

尝试这个

$('tr:not(:contains("me hussy")):not(:first)').remove();

You should use thead and tbody to separate the rows but this should work;

$(function() {
    var $table = $('table#byID');
    var $bodyRows = $table.find('tr').not(':first'); // Exclude the first row
    var hasEmptyTds = $bodyRows.find('td').filter(function() { // Filter by text, could also use the :contains selector
        return ($(this).text() != 'me hussy')
    }).length > 0;

    if (hasEmptyTds) {
        $bodyRows.remove(); // Remove all table body rows
    }
});

If you need to re-use the functionality, wrap it in a function, otherwise you can just replace the mustMatchString in the jQuery line below. To remove the first item, use the jQuery .slice method.

function runRemoval(mustMatchString) {
   jQuery('tr').slice(1).each(function() {
       if(!jQuery('td:contains("' + mustMatchString + '")', this).length) {
           jQuery(this).remove();
       }

   });
}

runRemoval('me hussy')​;

http://jsfiddle.net/steveukx/D6Hkh/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM