How to check if a div has a class from multiple classes in jquery

I have a dynamic div that can generate over 1000 different classes ... its a wordpress theme.

Now I want to check if the div has one of 52 classes.

.bg1, .bg2, .bg3, etc. etc.

I know that you can use hasClass ();

But how can I check each of them and then get the value. For example, here is a div, as it stands

<div id="wordpresspost" class="bodyclass post-id-193 wordpresswrap bg1"></div>

Please note that I really don't know jquery: D

I thought it would be something like this, but logically this does not make sense to me :(

var divclass = $("#wordpresspost").hasClass('bg1, bg2, bg3, bg4, bg5, bg6');

if(divclass == true){
    var divsclass = $(this);
}

I need to know the class because I want to change it, for example, I would like .removeClass and then addClass a new class without changing the rest, since they are dynamic

Thanks in advance for your advice :)

+5
4

.is():

var divclass = $("#wordpresspost").is('.bg1, .bg2, .bg3, .bg4, .bg5, .bg6');
+13

.

, , bg [something],

if($("#wordpresspost[class^=bg]").length > 0)
{
....
}

, , .

$("#wordpresspost[class^=bg]").each(function(){
     this.className = this.className.replace(/\bbg.*?\b/g, 'newclass');
});
+4
var el = document.getElementById('wordpresspost');
var regxpr = /\b(bg(?:[1-9]|[1-4]\d|5[0-2]))\b/g, match;
while(match = regxpr.exec(el.className)){
    // match[1] contains the current matching class
    console.log(match[1]);
    // Then you can do:
        $(el).removeClass(match[1]).addClass(replacementForMatch);
}

Jsfiddle

0
source

If you are looking for bg * in only one element, you can just use a simple regular expression.

 var hasBg = /bg[\d]+/.test(document.getElementById("mydiv").className);
-1
source

All Articles