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.
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.
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.
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.
(function($) {
jQuery.fn.extend({
prependClass: function(newClasses) {
return this.each(function() {
var currentClasses = $(this).prop("class");
$(this).removeClass(currentClasses).addClass(newClasses + " " + currentClasses);
});
}
});
})(jQuery);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With