Search code examples
jqueryclassprefix

prefix a class name with jquery


my question seems simple but I don't find a solution. I have some code on my web page like this :

<code class="bash">
...
<code class="markdown">

And I would like to use Prism library to have a syntax highlighting. But it requires to have a class like this

<code class="language-bash">
...
<code class="language-markdown">

So my question is, how in JQuery do I add the "language-" before the language naming ?

I have searched a lot, but prepend does not work with class and functions on class like addClass, toggleClass etc. does not store the actual class to add the prefix.

Any idea ?

Thank you very much.


Solution

  • you have to store every class in a var and concat it with the prefix then remove the old class and set the new one .

    $( "code" ).each(function( index , elm ) {
      var oldClass = $(elm).attr('class');
      newClass = 'language' + classVal ;
      $(elm).removeClass(oldClass);
      $(elm).addClass(newClass);
    });