Search code examples
jqueryjquery-selectorscustom-data-attribute

Jquery how to select elements containing specific value(s) in data attribute array?


let's say I have the following elements

<div data-tags="[8,18,32,52,53,56]"></div>
<div data-tags="[8,2,3]"></div>
<div data-tags="[4,6,10]"></div>

Now I want to select elements having "8" in their data-tags attribute, how would I do that with jquery? I'm trying $('[data-tags~=8]') also $('[data-tags~="8"]') but neither of them work. Any help is appreciated.

EDIT: I don't think $('[data-tags*=8]') would be a solution since it would also include items with values of 18, 86 804 etc. right?


Solution

  • You can use the following:

    var found = $('div[data-tags]').filter(function() {
      return JSON.parse($(this).attr("data-tags")).indexOf(8) > -1
    })
    

    Demo

    var found = $('div[data-tags]').filter(function() {
      return JSON.parse($(this).attr("data-tags")).indexOf(8) > -1
    })
    var found2 = $('div[data-tags]').filter(function() {
      return JSON.parse($(this).attr("data-tags")).indexOf(18) > -1
    })
    console.log("Found",found.length, "by number 8");
    console.log("Found",found2.length, "by number 18");
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div data-tags="[8,18,32,52,53,56]"></div>
    <div data-tags="[8,2,3]"></div>
    <div data-tags="[4,6,10]"></div>