Jquery select elements by class using name from variable

I want to do something in jQuery for all elements that match a specific class name. The class name comes from a variable. How to make a choice using a class using my variable?

var x = $(this).attr('href').slice(1); 

this will set x equal to the class name I want.

now I want to select all elements with this class name

I try things like this but it doesn't work

 $(.x.show().addClass('active').siblings().hide().removeClass('active'); 

basic basically I want to work on all elements where class = x

Finally, instead of setting x the class name, can I just get an array classes in the first assignment of the variable?

i.e. instead

 var x = $(this).attr('href').slice(1); 

Can I do this [pseudo code]:

 var x = classname is $(this).attr('href').slice(1); 
+4
source share
2 answers

A selector is nothing but a string. So you can use

 $('.' + classname) 

where classname is a variable that contains a specific class name

+20
source

try changing your code as follows

 $('.' + x).show().addClass('active').siblings().hide().removeClass('active'); 
+6
source

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


All Articles