summu
summu

Reputation: 398

selecting class name as variable for more than 2 words in jQuery

I'm trying to figure out if it's possible to select a div that contains more than 2 words as a class name in a variable. i.e, $("div[class='LIKES & DISLIKES']") this works fine but the problem is i have this class name LIKES & DISLIKES in a variable, I cant use variable in $("div[class='+ variable +']"). I tried something

var element = document.getElementsByClassName(variable)

but this gives me HTML collection which i dont know how to retrieve my div elements from that.

So I defined a text in the class name so I can hide all by using $("[class*='showtab']").hide() and show that that class for which anchor tag has been clicked $(".showtab"+lab).show() this works fine till two-word class name i.e. Style cat but it's not working for more than 3 words class name i.e. LIKES & DISLIKES

This works fine for $('.showtabStyle.cat') but not for $('.showtabLIKES.&.DISLIKES') but I am having LIKES.&.DISLIKES in a variable which I append it to the text showtab

My code do something like this

 $(document).on("click", ".nav-link-in", function (e){
     var labtemp = $(this).text().trim().replace(/\s+/g, ".");
     var lab = labtemp.replace(/\([\s\d\/]+\)/, ""); // this to remove extra space for `LIKES & DISLIKES` and replace it with .this gives `LIKES.&.DISLIKES` as i am removing number within bracket also
     $("[class*='showtab']").hide();
     $(".showtab"+lab).show();
  }

this code works fine for one/two word class name but not for more than two.

$("div[class='showtabLIKES & DISLIKES']") works great but as i said i have class name LIKES & DISLIKES in a variable.

Upvotes: 0

Views: 897

Answers (1)

Bram Vanroy
Bram Vanroy

Reputation: 28505

A single class name cannot contain more than one word, separated by spaces. That's just not allowed. So if you are saying you have one class "likes & dislikes", that's not valid. Those are probably three classes (if & is a valid classname, not sure). If you mean that you have two variables for two classes, and you want to select elements that have both of these classes then you should do:

$("."+var1+"."+var2)

With template literals you can even do:

$(`.${var1}.${var2}`)

Upvotes: 1

Related Questions