0

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>
</body>

Problem: currently only exact matches work:

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

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!

Chumtarou
  • 313
  • 5
  • 15
  • Possible duplicate of [jQuery: using 'starts with' selector on individual class names](http://stackoverflow.com/questions/2178416/jquery-using-starts-with-selector-on-individual-class-names) – 4castle Jul 25 '16 at 03:59
  • split and get the number from body class and use **ends with** css selector to match. [Just for your reference](https://api.jquery.com/attribute-ends-with-selector/) Attribute Ends With Selector [name$=”value”] – Braj Jul 25 '16 at 04:02

1 Answers1

1

Try the following loop

$('[class^=bar]').each(function(i,v){
   var numb = $(this).attr('class').split('-')[1];
  if ($('body').is('.foo-'+numb)) {
   $(this).addClass('bodySharesClass');
   }
});

demo

madalinivascu
  • 32,064
  • 4
  • 39
  • 55