1

I have this basic code which hides the closest tr if .foo contains a string:

$('.foo:contains("blah")').each(function() {
  $(this).closest('tr').hide();
 });

but the time has come that "blah" is not the only string I need to check for, I realise I now need to use an array but not sure how.

I took a wild guess and tried:

var arr = ['blah', 'foo', 'bar'];

$('.foo:contains("+arr[]+")').each(function() {
      $(this).closest('tr').hide();
     });

but to no avail.

3 Answers 3

3

You're close, however you'll need to loop over your array as well to check each value.

var arr = ['blah', 'foo', 'bar'];

var i=0;
for (; i<arr.length; i++) {
    $(".foo:contains('"+arr[i]+"')").each(function() {
         $(this).closest("tr").hide();
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, will tag as answer when time allows.
2
var arr = ['blah', 'foo', 'bar'];

$('.foo').each(function() {
    if($.inArray($(this).text(),arr)!==-1 ) {
      $(this).closest('tr').hide();
    }
     });

https://api.jquery.com/jQuery.inArray/

Or, with filter(): http://api.jquery.com/filter/

$( ".foo" )
  .filter(function( ) {
    return $.inArray($(this).text(),arr)!==-1;
  }).closest('tr').hide();

Comments

-1

Something like this should work (although there are probably much better ways of doing it).

var arr = ["John", "Jane", "Mike", "Ted"];
arr.forEach(function(val){
   $(".foo:contains('" + val + "')").each(function(){
       $(this).closest('tr').hide();
   });
});

1 Comment

val needs to be in seperate quotes inside the selector for .foo:contains in order to run properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.