I’ve been looking for an answer in SO, but I don’t get a straight answer or they’re for languages other than JavaScript. I want to use regular expression to look for a class name in a list of classes.
So for example I have this HTML and I want to check if it has the class hidden somewhere in the list of classes:
<div class="target box hidden"></div>
I’m using this JS code, but it doesn’t work:
// ON CLICK DO THE BELOW:
var divs = document.getElementsByTagName('div'),
re = /\bhidden\b/gi, //here's the regEx
i;
for (i = 0, max = divs.length; i < max; i += 1) {
if (divs.className === 'targets') {
var targets = divs[i];
if (targets.match(re)) {
targets.replace('hidden', '');
} else {
targets.className = 'target box hidden';
}
}
}
Basically, I wanna do a show/hide functionality, i.e. if hidden class is present then hide element, otherwise show element.
Many Thanks
Hope the code can be helpful.