I have a bunch of list items with an attribute. I want to select only two or three of these at a time. Currently I am split
ing a comma-separated list of ids then creating an array of selectors for jQuery to return:
var ids = $(this).text().split(','); //e.g. text = 1,13,27
var selectors = [];
for (var index in ids)
{
selectors.push('.container ul.class li[data-id="'+ids[index]+'"]');
}
$(selectors.join(',')).addClass('active');
This appears to be quite an expensive approach for Firefox. Is there a way to optimise this so I can select any li with the data-id attribute containing any of the ids?
Something similar to the below, but selecting any of the values?
var ids = $(this).text().split(','); //e.g. text = 1,13,27
$('.container ul.class li[data-id~="' + ids + '"]').addClass('active');
[edit]
Thanks to @Alnitak's comment I have changed my loops to:
var ids= $(this).text().split(',');
var length = ids.length;
for (var i=0; i<length;i++)
{
selectors.push('.container ul.class li[data-id="'+ids[i]+'"]');
}
This has delivered a big improvement, but is there any more I can do?
Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.
Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.
attributeStartsWith selector Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.
The [attribute*="value"] selector is used to select elements whose attribute value contains a specified value.
How about:
var ids = "21,5,6,7,10".split(",");
// selector produced: [data-id='21'],[data-id='5'],[data-id='6'],[data-id='7'],[data-id='10']
$("[data-id='" + ids.join("'],[data-id='") + "']").addClass("active");
http://jsfiddle.net/3MNDy/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With