Reputation: 4742
Say i have a number, 3
.
I'm looking for a way to determine if a given set of jQuery objects contains the number 3 in their attribute. this attribute is often a csv containing ids of countries. could contain one number, could contain multiple.
example tag:
<li data-regions="3,52,30">
<a data-href="/explore/barbados/people/some-person">Some Person</a>
</li>
ideally i'd be able to determine if a given list item has the region like so
var number = 3;
var els = $('li[data-regions:contains('+number+')]"');
Any ideas? if not, do you know how i might be able to extend jQuerys attribute selectors to take a parameter?
Upvotes: 0
Views: 53
Reputation: 771
Why don't you just break this into pices:
var number = 3;
/* First, fetch all li elements that has data-regions attribute */
var els_candidates = $('li[data-regions]');
var els = [];
els_candidates.each(function(index) {
/* Then evaluate if id exists, this way you check for ids, not only chars */
var regionsArray = $(this).data('regions').split(',');
if (regionsArray.indexOf(number+'') !== -1) {
els.push($(this));
}
});
console.log(els);
I am assuming that you need to discriminate the id: 3 (as in your example), and not just the character 3. For example,
<li data-regions="1,8,52">
<a data-href="/explore/barbados/people/some-person">Some Person</a>
</li>
Would be evaluated true, if you search for the number 5, instead for the id: 5. That's why I split into pieces the solution to avoid the error.
Upvotes: 1
Reputation: 430
The existing answers suggest *=
which will lead to many false positives. If you can change the data-regions attribute to be space-separated ("3 52 30"
), you can use the attribute contains word selector (~=
) like so:
Html:
<li data-regions="3 52 30">
<a data-href="/explore/barbados/people/some-person">Some Person</a>
</li>
And the JS:
var number = 3;
var els = $('li[data-regions~='+number+')]"');
Upvotes: 2
Reputation: 2040
Use li[data-regions*='3']
it selects all elements with tag name li that have attribute data-regions whose value contains 3
Upvotes: 0