Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery addClass() to first position of multiple classes

Tags:

jquery

what it does:

<p class="foo"></p>
$('p').addClass('bar');

output:

<p class="foo bar"></p>

what i need:

<p class="bar foo"></p>

So is it possible to add a class to an element to the first position?

edit (context): theres a split function on the last class right now. if another class is added its appended to the second split array as well.

like image 227
ggzone Avatar asked Jan 22 '13 15:01

ggzone


People also ask

Can we add more than one CSS classes to the selected elements using the addClass () method?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

What is the difference between using addClass () method to CSS ()?

addClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements. toggleClass() - Toggles between adding/removing classes from the selected elements. css() - Sets or returns the style attribute.

Can you add multiple classes to an element jQuery?

Approach: First select the element to which multiple classes will be added. Then use addClass() method to add multiple classes to the element and removeClass() method to remove multiple classes.


1 Answers

 (function($) {

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

})(jQuery);
like image 78
user3670510 Avatar answered Oct 18 '22 01:10

user3670510