1
$('.list_body').each(function(){
     var job_no = $(this).data('job_id');
     if($.inArray(job_no, return_data)) {
         $.noop();
     }
     else {
         $(this).closest('div.list_body').remove();
     }
});

.list_body data-attribute holds a job id reference.

What I need to do is remove the particular .list_body div if the job id is not included in the array return_data.

Not sure if the .each() function is the best practice here as currently it seems to get rid of a div even though the job id is in the array.

Reyno
  • 583
  • 13
  • 28
Sideshow
  • 1,321
  • 6
  • 28
  • 50
  • 1
    You need to show the HTML as well – RiggsFolly Jul 18 '13 at 12:14
  • 4
    and `$.inArray` returns `-1` if it's not in the array, so if the `job_id` is the first in the array, the element is getting removed anyway. And if it's not in the array, `-1` is still going to be truthy. – kalley Jul 18 '13 at 12:17

2 Answers2

3

Firstly, $.inArray returns -1 when not found, so there's an immediate logic flaw. Secondly, this refers to the element you want to remove, so looking for the closest with the same selector is redundant. Try this:

$('.list_body').each(function(){
    var $el = $(this);
    if ($.inArray($el.data('job_id'), return_data) == -1) {
        $el.remove();
    }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

Try

var return_data = [2]

$('.list_body').each(function(){
    var job_no = $(this).data('job_id');
    if($.inArray(job_no, return_data) > -1) {
        $(this).closest('div.list_body').remove();
    }
});

Demo: Fiddle

A better solution will be

$('.list_body').filter(function(idx, el){
    return $.inArray($(this).data('job_id'), return_data) > -1;
}).remove();

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531