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 spliting 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?
for ... inon arrays - it's for enumerating object keys, not array indices.for ... inforfor(var i = 0; i < length; i++). This has delivered a big improvement, but is there any more I can do?