Georgi Antonov Georgi Antonov - 2 years ago 85
Javascript Question

css select all elements that match specific class combination

Lets say I have these divs in my html:

<div id="div1" class="class1 aa class2 bb class3 cc class4 dd class5 ee"></div>
<div id="div2" class="class1 ff class2 gg class3 hh class4 ii class5 jj"></div>
<div id="div3" class="class1 aa class2 bb class3 mm class4 nn class5 oo"></div>

And I have the following strings:

var string1 = "class1 class2 class3 class4 class5";
var string2 = "aa class2 class3 class4 class5";
var string3 = "ff gg hh ii jj";
var string4 = "aa bb class3 class4 class5";

Ok so I'm trying to create a Jquery selector that gets one of the strings and selects as follow:

string1 //should select all 3 divs
string2 //should select div1 and div3
string3 //should select div2
string4 //should select div1 and div3

So the idea is that the selector gets the string and if all classes from the given string(5 classes) MATCH the div classes, the div gets selected.I have tried something like this but didint work.

$('div[class=' + stringnumber + ']').css(dosomething);

Answer Source

Given that you don't actually want to match the entire class attribute string value, use a multi-class selector.

var string1 = '.class1.class2.class3.class4.class5';

$('div' + string1).css(doSomething);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download