2

I have seen a brunch of solution about how to show/hide the div which do not contains(or contains) specific keywords but none of them do help.

So far I have done some codes like this:

<div class="media">Title : orange</div>
<div class="media">this is something about orangessss yolo</div>
<div class="media">Title : apple</div>
<div class="media">this is something about apple yolo</div>

<button id="filter">test</button>

And I have a method to fliter the elements:

        var KeywordArr = ["orange","orangessss"];

$('#filter').click(function () {  
        var key = $(".media"); 
        var word= key.find(".media").html();
            if(!word && word.toLowerCase().match([KeywordArr])) {
            $(".media").css("display", "none");
        }
});

These codes suppose to add "display:none" to every "media" class which does not contains any keywords included in the array. But it's not working as my exception.

So how can I hide all the elements when the "< div"> do not have the value contain in keywordArr?

Solution:

 $('#filter').click(function () {  

            var elems = $(".media");
            var KeywordArr = ["orange", "orangessss"];
            var res = $();
            for (var i = 0; i < KeywordArr.length; i++) {
              res = res.add(elems.filter(":contains('" + KeywordArr[i] + "')"));
            }
            elems.not(res).hide();

    });
Anson Aştepta
  • 1,125
  • 2
  • 14
  • 38

2 Answers2

2

Try to use :contains() selector at this context,

var elems = $(".media");
var KeywordArr = ["orange", "orangessss"];
var res = $();

for (var i = 0; i < KeywordArr.length; i++) {
  res = res.add(elems.filter(":contains('" + KeywordArr[i] + "')"));
}

elems.not(res).hide();

Also note that contains selector is case sensitive.

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • Thanks, it seem working now, but i need to do some modification, by the way am i able to make it not case sensitive? – Anson Aştepta Feb 28 '16 at 18:22
  • @anson920520 That is how the api was written. But you can override its behavior. Refer [this](http://stackoverflow.com/questions/2196641/how-do-i-make-jquery-contains-case-insensitive-including-jquery-1-8) for more info. – Rajaprabhu Aravindasamy Feb 28 '16 at 18:24
0

To keep your code more declarative you can use array foreach. also make sure to keep you variable names all lowercase.

var elems = $(".media");
var keywordArr = ["orange", "orangessss"];
var res = $();

keywordArr.forEach(function(keyword){
    res = res.add(elems.filter(":contains('" + keyword + "')"));
});

elems.not(res).hide();

Also if you can write the Same code with ES6 Template literals, here is a link to Demo

const elems = $(".media");
const keywordArr = ["orange", "orangessss"];
let res = $();

keywordArr.forEach(
    (keyword) => res = res.add(elems.filter(`:contains(${keyword})`))
);

elems.not(res).hide();
Mahdi Pedram
  • 689
  • 6
  • 12