Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery hide elements if matched to list regardless of order

I need to hide span elements if they match words in a wordList.

HTML:

<span class="wordBank_Words">
     <span word="hello"></span>
     <span word="you"></span>
     <span word="hi"></span>
</span>        

JavaScript:

wordList = ['hello', 'how', 'are', 'you'];

$('.wordBank_Words span').each(function (index, val) {
    if ($(this).attr('word').match(wordList)) {
        $(this).hide();
    }
});

So, if done correctly, it should hide 'hello' and 'you', but not 'hi'

If I do match('hello'), this correctly hides 'hello' span from the HTML element list.

But I need to loop through each span element in wordBank_Words, and compare them against each word in the wordList, and only hide if there is a match. They need to be compared regardless of order.

How can this be done?

like image 822
user3871 Avatar asked Dec 18 '22 23:12

user3871


2 Answers

No need of looping over all the elements.

You can create an attribute-value selector from array by joining them to form the correct selector.

'[word="' + wordList.join('"], [word="') + '"]'

will create a selector as

[word="hello"], [word="how"], [word="are"], [word="you"]

which then can be passed to jQuery.

Demo

var wordList = ['hello', 'how', 'are', 'you'];

var selector = '[word="' + wordList.join('"], [word="') + '"]';

$('.wordBank_Words').find(selector).hide();
span {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<span class="wordBank_Words">
  <span word="hello">Hello</span>
  <span word="you">You</span>
  <span word="hi">Hi</span>
  <span word="not">Not Found</span>
</span>

You can also use attr/prop methods as follow

var wordList = ["hello", "how", "are", "you"], re = wordList.join("|");

$(".wordBank_Words span").attr('word', function(index, val) {
  if (wordList.indexOf(val) > -1)
    $(this).hide();
  return val;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<span class="wordBank_Words">
  <span word="hello">hello</span>
  <span word="you">you</span>
  <span word="hi">hi</span>
</span>
like image 115
Tushar Avatar answered Mar 15 '23 06:03

Tushar


You can use Array.indexOf() to check whether the word exists in the array like

var wordList = ['hello', 'how', 'are', 'you'];

$('.wordBank_Words span').each(function(index, val) {
  $(this).toggle(wordList.indexOf($(this).attr('word')) == -1)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="wordBank_Words">
  <span word="hello"></span>
  <span word="you"></span>
  <span word="hi"></span>
</span>
like image 37
Arun P Johny Avatar answered Mar 15 '23 06:03

Arun P Johny