Select element in jQuery when one of two possible .data attributes has the desired value

Viewed 25

My question is rather simple but I couldn't find an existing answer:

I want to select a subset of elements if one of their two possible data attributes is "X".

My selector looks currently like this:

$('.line').data('identifier1', 'X');

I would like to add to the same selector .data('identifier2', 'X') using an OR statement, if that's possible with jQuery?

So the result should be that all .line elements are chosen if they have the value 'X' in either their data-identifier1 or data-identifier2.

Here is a snippet with only the OR statement missing:

let myCollection = $('.line').data('indentifier1', "X");

console.log(myCollection);

//myCollection should get divs 1,3,4 but not 2
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="line" data-identifier1="X" data-identifier2="Y">1</div>
<div class="line" data-identifier1="Y" data-identifier2="Y">2</div>
<div class="line" data-identifier1="Y" data-identifier2="X">3</div>
<div class="line" data-identifier1="X" data-identifier2="X">4</div>

2 Answers

You can use each() and a array to store each div inside

let DivsLine = $('.line');
let myCollection = new Array();

$(DivsLine).each(function(index, value){
  let identifier1 = $(this).data('identifier1');
  let identifier2 = $(this).data('identifier2');
  
  if (identifier1 == 'X' || identifier2 == 'X') {
    myCollection.push($(this).text());
  }
});

console.log(myCollection);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="line" data-identifier1="X" data-identifier2="Y">1</div>
<div class="line" data-identifier1="Y" data-identifier2="Y">2</div>
<div class="line" data-identifier1="Y" data-identifier2="X">3</div>
<div class="line" data-identifier1="X" data-identifier2="X">4</div>

You can query data attributes like this and use , as an or.

 let myCollection = $('.line[data-identifier1="X"],.line[data-identifier2="X"]');
 console.log(myCollection);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="line" data-identifier1="X" data-identifier2="Y">1</div>
<div class="line" data-identifier1="Y" data-identifier2="Y">2</div>
<div class="line" data-identifier1="Y" data-identifier2="X">3</div>
<div class="line" data-identifier1="X" data-identifier2="X">4</div>

Related