How do I use .filter to return multiple values?

Let's say I have a div, with some CSS and javascript:

var someCSS = {
  color: 'red',
};
         

$(".test > .sub").filter(function(index) {
   return $(this).text() == 'hello';
 }).css(someCSS);
      

.test {
  color: green;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='test'>
  <div class='sub'>hello</div>
  <div class='sub'>stackoverflow</div>
</div>
      

Run codeHide result


The above will color "hello" in red, but I don't understand how to add more values โ€‹โ€‹like "hello" and "stackoverflow". I obviously can't do it return $(this).text() == 'hello' || 'stackoverflow';

, but I just can't figure out what to do!

Any suggestions would be appreciated :)

+3


source to share


4 answers


Use an array of values โ€‹โ€‹and then check it, that way you can add more values โ€‹โ€‹as you like and then you can just use Array.prototype.indexOf

.

var arr = ['hello', 'stackoverflow'];

      



and then

return arr.indexOf($(this).text()) > -1;

      

+4


source


Close, you need to compare again:



return $(this).text() == 'hello' || $(this).text() == 'stackoverflow'

      

+1


source


$(".test > .sub").filter(function(index) {
   return $(this).text() == 'hello' || $(this).text() === 'stackoverflow';
 }).css(someCSS);

      

or

var values = [
  'hello',
  'stackoverflow'
]

$(".test > .sub").filter(function(index) {
   return values.indexOf($(this).text()) > -1 
 }).css(someCSS);

      

+1


source


My own problem is using Array.prototype.indexOf()

:

$(".test > .sub").filter(function(index) {
   return ['hello','stackoverflow'].indexOf($(this).text().trim()) > -1;
 }).addClass('someCSS');

      

The above approach allows you to use the array of strings you want to search for, rather than explicitly comparing and evaluating a series of strings in an anonymous function; although in this example I have constructed this array in the same function for brevity.

$(".test > .sub").filter(function(index) {
  return ['hello','stackoverflow'].indexOf($(this).text().trim()) > -1;
}).addClass('someCSS');
      

.someCSS {
  color: #f00;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='test'>
  <div class='sub'>hello</div>
  <div class='sub'>stackoverflow</div>
</div>
      

Run codeHide result


Literature:

+1


source







All Articles