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.

2
  • 1
    You need to show the HTML as well Commented Jul 18, 2013 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. Commented Jul 18, 2013 at 12:17

2 Answers 2

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();
    }
});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.