3

I need to select div by data, with multiple data value.

<div data-name='["ab","abcd","abcdf"]' />

$("div[data-name*='ab']")  

But this solution selects all divs that contain 'ab'. I need to select only divs that contain only 'ab'.

EDIT: the best solution:

<div data-name='["ab","abcd","abcdf"]' />

$("div[data-name*='ab\"']")  
1
  • ok then try $(div[data-name*='"ab"']) Commented May 22, 2014 at 10:28

2 Answers 2

3

It's probably best to .filter the list:

$('div[data-name]').filter(function() {
   return $.inArray("ab", $(this).data('name')) >= 0
});

i.e. select any div with a data-name attribute, and then explicitly pick out those whose array value contains the desired element.

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

8 Comments

+1. was about to paste a asolution like this :-) , just found out that $(this).data('name') ia already an array :-)
? var a=$('div').eq(0).data('name'); alert({}.toString.apply(a)) //Array
(all im saying is that $(this).data('name') in this case is a pure JS array)
Hmm, you're right, but for some reason .indexOf wasn't working... but does now. Weird. In any event, $.inArray is more portable.
p.s. for the data to be an array it must be in proper JSON syntax. If you use the wrong style of quotes it fails.
|
0

Try this:

HTML:

<div data-name='["ab","abcd","abcdf"]' />
<div data-name='["b","abcd","abcdf"]' />
<div data-name='["v","abcd","abcdf"]' />
<div data-name='' />
<div />

Jquery:

var  divList = [];
divList = $('div').filter(function() {
    if($(this).data('name') != "")
   return $.inArray("ab", $(this).data('name')) >= 0
});
alert(divList.length)

Working Example

2 Comments

Why convert the jQuery object into a native array?
@Alnitak: Yes you are right, it already a array object. Thank you to update me for my silly mistake :)

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.