Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Selecting DOM Element by data-attribute with multiple Identifiers in it

Note: this isn't a basic question on Querying by data-attributes

The problem I'm having is that I have certain elements like so:

<div data-step="1, 4">

I have figured out how to step through each [data-step] and extract the 1, 4 and create events for them, etc.

Let's say I'm trying to Query and grab this exact data-step but all I'm given is: 4

$('[data-step="4"]') 
// this won't work of course

$('[data-step="1, 4"]')
// obviously this will work, but at this point I'm only given the index
// which will only be ONE of these numbers

Basically given (for examples sake, 4) How can I easily Query the selector to go out and grab [data-step="1, 4"]?

All I'm able to come up with is a loop, that goes through each data-step, strips out everything and sees if there is a match. Is there an easier way potentially?

like image 447
Mark Pieszak - Trilon.io Avatar asked Jan 29 '26 19:01

Mark Pieszak - Trilon.io


2 Answers

~= will find element with an attribute which has a value containing a given word, delimited by spaces. Works in your case also.

$('[data-step~="4"]')

*= will find element with an attribute which has a value containing the given substring.

$('[data-step*="4"]')
like image 94
Aleksandr M Avatar answered Feb 01 '26 10:02

Aleksandr M


You may also use filter solution:

var search = 4;
$("[data-step]").filter(function() {
    return $.inArray("" + search, $(this).data("step").split(/,\s*/)) !== -1;
});
like image 38
VisioN Avatar answered Feb 01 '26 10:02

VisioN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!