jqueryduplicatesremoveclass

How do I remove duplicated classes on the same element


How do I remove duplicated classes on the same element with JQuery?

Example:

<a href="#" class="foo foo">link</a>

I want just one class in this element, as shown below:

<a href="#" class="foo">link</a>

I've tried it but unsuccessfully. Thanks


Solution

  • You can remove the existing classes using removeClass() and add one back using addClass() as follows:

    $("a").removeClass("foo").addClass("foo");
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#" class="foo foo">link</a>


    Update (As per comments)

    You can extend the jQuery function namespace as shown below for a more general solution which iterates over a jquery object and eliminates any duplicate class names:

    (function($) {
      $.fn.removeDuplicateClass = function(className) {
        return this.removeClass(className).addClass(className);
      };
      $.fn.removeDuplicateClasses = function () {
        this.each(function (i, element) {
            var arr = [],
            classList = $(element).attr("class").split(" ");
            $.each(classList, function (i, item) {
                if (arr.indexOf(item) < 0) {
                    arr.push(item);
                  }
            });
            $(this).attr("class", arr.join(" "));
        });
        return this;
      };
    })(jQuery);
    
    $("a").removeDuplicateClasses(); // or $("a").removeDuplicateClass("foo");
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul>
      <li>
        <a href="#" class="foo foo">foo dup</a>
      </li>
      <li>
        <a href="#" class="bar foo bar">bar dup</a>
      </li>
    </ul>