I have a dynamic div which can generate over 1000 different classes... its a wordpress theme.
Now i am wanting to check if a div has one of 52 classes.
.bg1, .bg2, .bg3 etc etc...
I know that you can use hasClass();
But how do I check for each one and then get the value. For instance here is the div as it stands
<div id="wordpresspost" class="bodyclass post-id-193 wordpresswrap bg1"></div>
Please bare in mind I dont really know jquery :D
I was thinking 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 instance i would like to .removeClass and then addClass a new class without changing the others as they are dynamic
Thanks in advance for the advice :)
I have a dynamic div which can generate over 1000 different classes... its a wordpress theme.
Now i am wanting to check if a div has one of 52 classes.
.bg1, .bg2, .bg3 etc etc...
I know that you can use hasClass();
But how do I check for each one and then get the value. For instance here is the div as it stands
<div id="wordpresspost" class="bodyclass post-id-193 wordpresswrap bg1"></div>
Please bare in mind I dont really know jquery :D
I was thinking 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 instance i would like to .removeClass and then addClass a new class without changing the others as they are dynamic
Thanks in advance for the advice :)
Share Improve this question asked Apr 25, 2013 at 19:20 RobertRobert 9254 gold badges15 silver badges36 bronze badges 1-
I'd do
if ( elem.className.seach( re ) > -1 ) { ...
– Šime Vidas Commented Apr 25, 2013 at 19:26
4 Answers
Reset to default 14Use .is()
:
var divclass = $("#wordpresspost").is('.bg1, .bg2, .bg3, .bg4, .bg5, .bg6');
You can use starts with selector.
Caveat with this is that if you have another class starts with bg[something] it would be impacted
if($("#wordpresspost[class^=bg]").length > 0)
{
....
}
In order to remove it probably regex might help.
$("#wordpresspost[class^=bg]").each(function(){
this.className = this.className.replace(/\bbg.*?\b/g, 'newclass');
});
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
If you are searching for bg* in only one element, you could just use simple regex.
var hasBg = /bg[\d]+/.test(document.getElementById("mydiv").className);