Search code examples
jquerylistvariablesalphabetical

Generate classes by alphabet extracting href element


So I have a list, example:

<ul>
 <li href="pages/ade.html">ade</li>
 <li href="pages/ate.html">ate</li>
 <li href="pages/aca.html">aca</li>
 <li href="pages/bes.html">bes</li>
 <li href="pages/bon.html">bon</li>
 <li href="pages/cas.html">cas</li>
<ul>

And I'm usign jquery to get the href attribute and then add a class to that element.

$("li > a[href^='/pages/a']").parent().addClass( "brand-a" );
$("li > a[href^='/pages/b']").parent().addClass( "brand-b" );
$("li > a[href^='/pages/c']").parent().addClass( "brand-c" );

So I don't want to write a function for each letter and I was thinking that I can use alphabet to do this. I found this looking around, but I don't know how to implement it.

alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');

Thanks


Solution

  • I think that you must loop, maybe something like this:

    'abcdefghijklmnopqrstuvwxyz'.split('').forEach(function(letter){
        $("li > a[href^='/pages/" + letter + "']").parent().addClass( "brand-" + letter + "" );
    });