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?

4
  • What is the value of the data-event you're trying to match with? Commented Feb 21, 2018 at 15:36
  • 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"]. Commented Feb 21, 2018 at 15:36
  • can you add html element you want to select Commented Feb 21, 2018 at 15:38
  • Yeah, it wasn't necessary but I added the LI element I'm selecting so it's clearer. Commented Feb 21, 2018 at 15:39

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

1 Comment

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 + '"]'.
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);

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.