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 them at a time. I am currently split with a comma-separated list of identifiers, and then creating an array of selectors to return jQuery:

 var ids = $(this).text().split(','); //eg 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 is a pretty expensive approach for Firefox. Is there a way to optimize this, so I can select any li with a data-id attribute containing any of the identifiers?

Something similar to the one below, but choose any of the values?

 var ids = $(this).text().split(','); //eg text = 1,13,27 $('.container ul.class li[data-id~="' + ids + '"]').addClass('active'); 

[edit]

Thanks to the comment by @Alnitak, I 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 improved significantly, but is there more to be done?

+6
source share
5 answers

What 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/

+9
source

You can use the filter method:

 $('.container ul.class li').filter(function() { return ids.indexOf($(this).data('id')) > -1; }).addClass('active'); 
+8
source
 var ids = $(this).text().split(','); $.each(ids, function(k, v){ $('.container ul.class li[data-id="' + v + '"]').addClass('active'); }); 
+4
source

It is best to select all the elements with the data-id attribute once, then filter this list based on the attribute value:

 var $matches = $('.container ul.class li[data-id]').filter(function() { return $.inArray(this.getAttribute("data-id"), ids); }); $matches.addClass('active'); // or whatever else you want to do 
+1
source

I think this will be a more optimized approach:

 var ids = $(this).text().split(','); //eg text = 1,13,27 var lis = $('.container ul.class li'); lis.filter(function() { return $.inArray($(this).data('id'), ids); }).addClass('active'); 
0
source

Source: https://habr.com/ru/post/947982/


All Articles