简体   繁体   中英

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?

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();
var $divs = $('div').filter(function() {
  // returns all divs with data-attr not equal 1 or 2 or 5
  return [1, 2, 5].indexOf(this.data('attr')) == -1;
});

HTML:

<div data-attr="2">not matched</div>
<div data-attr="5">not matched</div>
<div data-attr="6">matched</div>

Given a list of elements, you can use jQuery.not to exclude those elements from another selector

 $(function(){ // I want to process every div containing attr 3 and 4 var divs = $('div[data-attr="3"], div[data-attr="4"]'); console.log(divs); // logs 2 var notDivs = $('div[data-attr]').not(divs); console.log(notDivs); // logs the other 3 }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM