Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Select exact class structure

I am working on some functionality for a website. I am designing, and I am kind of stuck on something small. I want to hide divs that contain an exact class structure.

For example, if I give it the class selector ".class1.class2.class3", it will ONLY hide elements that have exact class structure. What I am doing now would hide elements like ".class1.class2.class3.class4", and I don't want that.

Any help would be greatly appreciated!

like image 723
Giovonni Avatar asked Aug 03 '26 05:08

Giovonni


2 Answers

In this particular case, you can use the .not() selector:

$('.class1.class2.class3:not(.class4)')

You can also do it with method chaining:

$('.class1.class2.class3').not('.class4')

Note that this doesn't necessarily select exactly .class1.class2.class3 with no other classes, it just prevents anything with class4 from being selected.

like image 54
Ben Lee Avatar answered Aug 04 '26 20:08

Ben Lee


I you want to match objects that ONLY have exactly those three class names and you want to be insensitive to the order of the class names or the amount of white space between them, then you can do it like this:

$('.class1.class2.class3').filter(function() {
     return(this.className.replace(/class1|class2|class3/g, "").replace(/\s*/g, "") == '');
});

If you want to only exclude a specific other class, then you can do it like this:

$('.class1.class2.class3').not('.class4')
like image 29
jfriend00 Avatar answered Aug 04 '26 21:08

jfriend00