0

I have an attribute for a set of HTML5 objects that is an array. Something like

<button attr=[1,0,0,0,1,1]>test</button>
<button attr=[1,1,0,0,1,1]>test</button>
...

How do I formulate a jQuery selector to match only elements whose n-th value of attr is 1? Something like $("attr[1]=1") that would only select the second button from this example (this syntax does not work, but I wrote it just to give an idea of what I need).

In my case I am not dealing with buttons but with other types of objects, I just wanted so simplify the context of the question.

2 Answers 2

3

You can use a custom filter to select only the matched elements.

<button data-attr="[1,0,0,0,1,1]">button 1</button>
<button data-attr="[1,1,0,0,1,1]">button 2</button>

Note that attr is not a valid html attribute for button. I'd suggest you use the data-attr instead. You can use .data('attr') to get the data back.

var selected = $('button').filter(function (idx) {
    var attr = $(this).data('attr');
    return attr && attr[1] == 1;
});
alert(selected.html());

jsFiddle Demo

Sign up to request clarification or add additional context in comments.

Comments

1

You can write your own selector like this (i called it "array", you can use a better name here):

jQuery.expr[':'].array = function (elem, index, match) {
    var params = match[3].replace(/^\s+|\s+$/g, '').split(/\s*,\s*/),
        attribute = params[0],
        arrayindex = parseInt(params[1]),
        matchvalue = params[2],
        value = JSON.parse($(elem)[attribute](attribute));
    return value[arrayindex] == matchvalue;
};

Then, use it like any other selector where the first parameter is the name of the attribute, the second parameter is the index in your array and the third parameter is the expected value:

$('button:array(attr,1,1)');

Fiddle: http://jsfiddle.net/pascalockert/uDnK8/2/

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.