Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery attribute selector where value contains value in array

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?

like image 221
Richard Parnaby-King Avatar asked Jun 24 '13 11:06

Richard Parnaby-King


People also ask

How do you find the element based on a data attribute value?

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.

How get data attribute value in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.

Which selects elements that have the specified attribute with a value beginning exactly with a given string?

attributeStartsWith selector Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.

Which of the following attribute selector represents elements with an attribute name of ATTR whose value is prefixed by value?

The [attribute*="value"] selector is used to select elements whose attribute value contains a specified value.


1 Answers

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/

like image 170
karim79 Avatar answered Oct 19 '22 13:10

karim79