How to put 2 elements concatenated with variable in a selector with jQuery?

Asked

Viewed 2,014 times

2

I have 2 variables and I want to put the same concatenated in just one selector with jQuery:

I know it’s possible to do it this way:

$(".classe1, .classe2").append(...);

But I want to concatenate these two classes with a variable and put the two inside a selector more or less like this (this example is giving error):

var to = $(".meunome").attr("id");
var from = $(".amigonome").attr("id");

$(".classe1'+to+', .classe2'+from+'").append(...);

1 answer

3


You got the id, so you have to use the '#' selector:

var to = $(".meunome").attr("id");
var from = $(".amigonome").attr("id");

$('#' + to + ', #' + from).append(...);
  • +1 Note that if there is more than one element with the class meunome and/or more than one with the class amigonome, this code will only select the first of each set.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.