Search code examples
jquerymatchcustom-data-attribute

jQuery check data-* attribute if it contains value with $(this) and then do something


HTML:

<!-- a class with a data-target attribute with a list of space-seperated values -->
<div class="class1" data-target="value1 value2 value3 ...">
    ...
</div>

<!-- and there might be more than one object with the same class but with same and/or different data-target values -->
<div class="class1" data-target="value4 value5 value2 ...">
    ...
</div>

jQuery:

// looping through each class1 to see if it contains a value and if so do something
$.each($('.class1'), function(){
    if ($(this)...) { // check if data-target of this specific object with class1 contains the value
        // do something
    }
});

to check if data-target of this specific object with class1 contains a value I want something akin to:

element[data-target~="value5"]

but on $(this)

I have tried:

if ($(this).attr('[data-target~="value5"]')) ... // doesn't work (don't know why)

if ($('.class1[data-target~="value5"]')) ... // works but apply to all class1 objects and not just the specific one I'm testing

if ($(this).data('target').match('value5')) ... // works but is akin to *= and I want all the match options like ~= |= ^= etc.

but for what ever reason... I need to be able to apply something equivalent to [data-target~="value*"] to $('this')

so 2 questions:

  1. why doesn't $(this).attr('[data-target~="value5"]') (or $(this).attr('data-target~="value5"') for that matter) work?
  2. how do I do what I want to do?

Solution

  • Some jquery methods take a selector and others do not.

    .attr() does not take a selector, so you can't use [data-target] in .attr(), just a simple string for the attribute name, .attr("data-target") - so this would work like your .data("target") example, where you use js to check the value as required.

    Instead you can use .is() or .filter():

    if ($(this).is('[data-target~="value5"]'))
    

    $.each($('.class1'), function(){
        if ($(this).is("[data-target~='value3']")) { 
            console.log("yes it is");
        }
        else
            console.log("no it's not");
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="class1" data-target="value1 value2 value3">target</div>
    <div class="class1" data-target="value1 value2 value5">target</div>