ggzone
ggzone

Reputation: 3721

jquery addClass() to first position of multiple classes

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.

Upvotes: 17

Views: 18759

Answers (6)

muka.gergely
muka.gergely

Reputation: 8329

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>

Upvotes: 0

J. Minjire
J. Minjire

Reputation: 1098

Here's another way to do it.

$('#foo').attr('class', 'new-class ' + $('#foo').attr('class'));

Upvotes: 5

user3670510
user3670510

Reputation: 171

 (function($) {

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

})(jQuery);

Upvotes: 17

Oscar Jara
Oscar Jara

Reputation: 14187

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');

Upvotes: 0

algorhythm
algorhythm

Reputation: 8728

function prependClass(sel, strClass) {
    var $el = jQuery(sel);

    /* prepend class */
    var classes = $el.attr('class');
    classes = strClass +' ' +classes;
    $el.attr('class', classes);
}

Upvotes: 8

Explosion Pills
Explosion Pills

Reputation: 191819

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');

Upvotes: 3

Related Questions