Chumtarou Chumtarou - 1 year ago 81
CSS Question

Check if similar (but not exact) class exists with Jquery

Wondering if there is a way to extend the following code to allow searching for a similar class but not exact.

My goal: to match foo-123 and bar-123 and append a class to the link with class bar-123 to indicate it is matched:

Structure of page:

(Foo- and Bar- are preset and are always the same. Only the numbers change.)

<body class="foo-123">
<a href="#" class="bar-123">Item 123</a>
<a href="#" class="bar-456">Item 456</a>
<a href="#" class="bar-789">Item 789</a>

Problem: currently only exact matches work:

function(i) {
var classes = this.className.split(/\s+/);
for (var i=0,len=classes.length; i<len; i++){
if ($('body').hasClass(classes[i])){

jsfiddle example

Thank you in advance.

Edit: quick note that this question differs from other posts as the prefix is set but the number is unknown. Other questions I have found focus on finding a specific class or specific word in a class. @madalin ivascu's answer is perfect and @Braj's comments helped as well, thanks!

Answer Source

Try the following loop

   var numb = $(this).attr('class').split('-')[1];
  if ($('body').is('.foo-'+numb)) {


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download