3

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?

2
  • 4
    If you can change your data-step attribute to be delimited by spaces, you can use $("[data-step~='4']"). Commented Jan 3, 2013 at 22:41
  • @ajshort Seems like the simplest solution here! Luckily I'm able to change that, much easier to handle this way. Cheers Commented Jan 3, 2013 at 22:52

3 Answers 3

4

~= 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"]')
Sign up to request clarification or add additional context in comments.

3 Comments

wow how did I not know about ~= !! The attributes contains word selector, very nice. This works perfectly! And to my suprise does not pick up things like [data-step=14] if I'm only doing ~=4. Thanks so much!
It is important to know that the provided selectors do not work for attributes like data-step="1, 4, 5" and data-step="1, 44" respectively.
@VisioN: *= will work for data-step="1, 4, 5" and finding 44 is not what OP is looking for if understand it correctly.
2

You may also use filter solution:

var search = 4;
$("[data-step]").filter(function() {
    return $.inArray("" + search, $(this).data("step").split(/,\s*/)) !== -1;
});

3 Comments

Very nice! For some reason I was getting Uncaught TypeError: Object 1 has no method 'split' until I changed it to .attr('data-step'). But this works perfectly as well!
@mcpDESIGNS It seems that you use the old version of jQuery =)
1.7.2 still yeah :/ Upgrading soon hopefully!
0

You need to use * before = it will return all data-step wich is contain substring 'value' $('[data-step*="value"]')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.