Search code examples
javascriptjqueryjquery-selectorsxor

jQuery XOR selector


From a set of divs I want to select all the divs that contain a specific attribute and then select all the divs that do not contain any of the attributes.

Example:

<div data-attr="1"></div>
<div data-attr="2"></div>
<div data-attr="3"></div>
<div data-attr="4"></div>
<div data-attr="5"></div>
var attrList = [3,4];

// I want to process every div containing attr 3 and 4
attrList.forEach(function(item){
    var div = $("[data-attr='"+item+"']");
    div.operation_here()
});

// but I also want to process the remaining divs that do not contain neither attr 3 and 4
/* HELP ME HERE - this would select divs with attr 1, 2 and 5 */

How to achieve this?


Solution

  • Make it steps by steps. First, select all div:

    var $div = $('div[data-attr]');
    

    Then, select those you need:

    var $valid_div = $div.filter(function(){
         return attrList.indexOf($(this).data('attr')) > -1;
    });
    

    Now you can do your operation on matching div with your variable:

    $valid_div.operation_here();
    

    To select remaining div, you can use .not():

    var $invalid_div = $div.not($valid_div);
    $invalid_div.operation_here();