-3

My question is asked before for using javascript variables with the Single jQuery selector, As in this post below.

How to use javascript variables in jquery selectors

But my question is how to use one variable with two or more selectors?

var itemId = $(this).closest('li').attr('id');

This is for one selector

var contentType = $('#' + itemId + ' .content-type');

But how to use itemId when i have two selectors in one row like below

var contentType = $('.content-type1, .content-type2');
SAFEEN 1990
  • 210
  • 1
  • 2
  • 12

2 Answers2

1

You do it the same way, by adding a , between 2 selectors.

As of, you are doing:

var contentType = $('#' + itemId + ' .content-type');

For 2 elements, you use ,:

var contentType = $('#' + itemId + ' .content-type1, #' + itemId + ' .content-type2');
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35
0

You can concat manually as much as you need but maybe you can do a selector prepare the following way so you can append n-times the variable easily:

var itemId = $(this).closest('li').attr('id');
var selector = '#{i}.content-type1, #{i}.content-type2, #{i}.content-type3'; // you can extend this as much as you like or even add a loop to construct content types
var finalSelector = selector.split('{i}').join(itemId); // doing the replace
var contentType = $(finalSelector);

Where {i} is just a fictive placeholder string. I think this is a bit more readable. Anyways your question is kinda strange when it comes to the

"or more selectors"

part logically. Maybe you need to change your code flow/implementation technique for whatever you are trying to achieve.

Samuil Petrov
  • 542
  • 1
  • 13
  • 24