what it does:
$(\'p\').addClass(\'bar\');
output:
<
(function($) {
jQuery.fn.extend({
prependClass: function(newClasses) {
return this.each(function() {
var currentClasses = $(this).prop("class");
$(this).removeClass(currentClasses).addClass(newClasses + " " + currentClasses);
});
}
});
})(jQuery);
Here's a no-hack solution for this:
$(".product").each(function(i, el) {
var cList = [];
$.each(this.classList, function(index, val) {
cList.push(val);
})
this.classList.remove(...cList);
cList.unshift("first-class");
this.classList.add(...cList);
// here it is
console.log(this.classList);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="product type-product status-publish">a</li>
<li class="product type-product status-publish">b</li>
<li class="product type-product status-publish">c</li>
</ul>
You can try this, live demo:
http://jsfiddle.net/oscarj24/eZe4b/
$('p').prop('class', 'bar foo');
Otherwise you will need to play around with addClass
and removeClass
to get bar foo
result in that order.
By the other hand, I don't get at all your question but if you just want to add bar foo
class to the first p
element just do this:
$('p').eq(0).prop('class', 'bar foo');
This should not be a dependency for you in any way at all because of the limited control you have over the className
string, but you can do this:
$("p").removeClass('foo').addClass('bar foo');
function prependClass(sel, strClass) {
var $el = jQuery(sel);
/* prepend class */
var classes = $el.attr('class');
classes = strClass +' ' +classes;
$el.attr('class', classes);
}
Here's another way to do it.
$('#foo').attr('class', 'new-class ' + $('#foo').attr('class'));