1

There's a similar answer here but it's somehow different and doesn't fit my case, I can't just do a join(): an array of strings as a jQuery selector?

I have a dynamic array that looks like this,

['abc', 'def', 'ghi']

I need to do a Selector string as follows including all these values as a data-event attribute as follows:

$('li.event[data-event="' + /*every element from the array*/ + '"]');

Is there a way to avoid looping?

gene b.
  • 8,520
  • 12
  • 76
  • 167

3 Answers3

3

Every element of the array data-event needs to be included in the Selector string shown. That is my selector. e.g.: .event[data-event="abc"], .event[data-event="def"], .event[data-event="ghi"].

In this case you need to build a separate selector for each element and join() them together. You can achieve that using map():

var arr = ['abc', 'def', 'ghi'];
var selector = arr.map(function(el) {
  return `.event[data-event="${el}"]`;
}).join(',');

$(selector).addClass('foo');
.foo { color: #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="event" data-event="abc">ABC</div>
<div class="event" data-event="def">DEF</div>
<div class="event" data-event="ghi">GHI</div>
<div class="event" data-event="xyz">XYZ</div>
Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
  • Just one comment. In IE11 the notation`${el}` doesn't work -- nor does the backtick, ```. I had to change it to `return '.event[data-event="' + el + '"]'`. – gene b. Feb 22 '18 at 15:35
0

An alternative solution without .map()

var arr = ['abc','def','ghi'];

var test = 'li.event[data-event="' + arr.join('"],li.event[data-event="') + '"]';

console.log(test);
Zenoo
  • 12,242
  • 4
  • 44
  • 63
0

The goal is to obtain a selector that looks like:

.event[data-event="abc"],.event[data-event="def"],.event[data-event="ghi"]

You can do this with join in a slightly different way:

var arr = ['abc', 'def', 'ghi'];

var part1 = '.event[data-event="';
var part2 = '"]';

var sel = part1 + arr.join(part2 + "," + part1) + part2;

console.log(sel);
freedomn-m
  • 24,983
  • 7
  • 32
  • 55