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>
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 :)
source to share
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;
source to share
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>
Literature:
- JavaScript:
source to share