1

I'm trying to get a function to prepend a name to my defined class.

The function is:

(function($) {

    jQuery.fn.extend({
        prependClass: function(newClasses) {
            return this.each(function() {
                var currentClasses = $(this).prop("class");
                $(this).removeClass(currentClasses).addClass(newClasses + " " + currentClasses);
            });
        }
    });

})(jQuery);

This was taken from this link: jquery addClass() to first position of multiple classes

I have a link like this:

<a class="half first3547" href="#">this</a>

I want it to become:

<a class="paid first3547" href="#">this</a>

I'm using this:

$("#mycontent a.half").removeClass("half").addClass("paid");

But that appends the class. It becomes this:

<a class="first3547 paid " href="#">this</a>

I don't understand how to implement the function so that it works with my code. I tried placing it above my script, but it doesn't do anything.

osakagreg
  • 537
  • 4
  • 19

1 Answers1

1

Use $("#mycontent a.half").removeClass('half').prependClass('paid');

(function($) {

  jQuery.fn.extend({
    prependClass: function(newClasses) {
      return this.each(function() {
        var currentClasses = $(this).prop("class");
        $(this).removeClass(currentClasses).addClass(newClasses + " " + currentClasses);
      });
    }
  });

})(jQuery);

$("#mycontent a.half").removeClass('half').prependClass('paid');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mycontent">
  <a class="half first3547" href="#">this</a>
</div>
sol
  • 22,311
  • 6
  • 42
  • 59