Mad
Mad

Reputation: 21

check if data attribute (array) contains value

is it possible to check if a data attribute (array) contains a specific value?

element looks like this:

<span id="el" data-id="[1, 2, 10, 3]"></span>
<span id="el" data-id="[4, 3]"></span>
<span id="el" data-id="[6]"></span>

I tried but (obviously) it didn't work:

$('#abcdef').find('[data-id*="3"]');

Upvotes: 1

Views: 1424

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

As you're trying to use the 3 as part of the selector to retrieve elements, you can use filter(), like this:

let id = 3;
$('.el').filter((i, el) => $(el).data('id').includes(id)).addClass('foo');
span { 
  display: block; 
  margin: 3px;
}
.foo { 
  background-color: #C00;
  color: #EEE; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="el" data-id="[1, 2, 10, 3]">1, 2, 10, 3</span>
<span class="el" data-id="[4, 3]">4, 3</span>
<span class="el" data-id="[6]">6</span>

Note that I removed the repeated id="el" as it's invalid and changed it to a class.

Upvotes: 0

dev-cyprium
dev-cyprium

Reputation: 768

One of the problems in your example is that multiple elements have the same id Unfortunately, this is not possible with HTML and I suggest you make them classes first.

As for your question, it's possible but you would have to do it like so:

$(function () {
  $(".element").each(function () {
     const arr = $(this).data('array');
     let text = 'Does not include 2';
 
     
     if (arr.includes(2)) {
         text = 'Does include 2';       
     }
     
     $(this).text(text);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element" data-array="[1,2,3,4]"></div>
<div class="element" data-array="[5,6,7]"></div>
<div class="element" data-array="[2,3]"></div>

If you don't want to find by class, you can also search by the data attribute, and then use the same code from above to check for presence of a value in the array:

$("[data-array]").each(...)

Upvotes: 1

Related Questions