0

I want to search through a class for elements that have data-id attribute that matches in the array, and hide them.

The HTML:

<li class="list" data-id="1">one</li>
<li class="list" data-id="2">two</li>
<li class="list" data-id="3">three</li>
<li class="list" data-id="4">four</li>

I have an array: var dataIDcheck = ['1', '3']

Any ideas on how I can search through the class .list and hide 1 and 3 (or whatever is in the array)?

JayDee
  • 1,633
  • 4
  • 21
  • 33

5 Answers5

2
var dataIDcheck = ['1', '3'];
$('[data-id="' + dataIDcheck.join('"], [data-id="') + '"]').hide();

http://jsbin.com/ojipaw/1/

Yoshi
  • 54,081
  • 14
  • 89
  • 103
1

You can use the filter and inArray function

 $('.list').filter(function(){
      return $.inArray($(this).data('id'),dataIDcheck) > -1
 }).hide(); // <-- hides any elements that have data-id found in array
wirey00
  • 33,517
  • 7
  • 54
  • 65
0
var ids   = [1, 3],
    count = ids.length,
    parts = [];

for (var i = 0; i < count; i++) {
    parts.push('[data-id="' + ids[i] + '"]');
}

var selector = parts.join(',');

var elems = document.querySelectorAll(selector);

This works with standard DOM (IE8+) and does not need any libraries. It also may make sense for you to see querySelectorAll() documentation.

Marat Tanalin
  • 13,927
  • 1
  • 36
  • 52
0
for (id in dataIDcheck) {
    $('.list[data-id=' + dataIDcheck[id] + ']').hide()
}
buttscicles
  • 3
  • 1
  • 4
0

why not jquery's inArray()

var dataIDcheck = [1, 3];


$('.list').each(function() {
    if($.inArray($(this).data("id"),dataIDcheck) > -1) {
      $(this).fadeOut(); 
    }
});

fiddle

AbstractChaos
  • 4,211
  • 1
  • 19
  • 28