jquery addClass() to first position of multiple classes

后端 未结 6 1341
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-11 16:04

what it does:

$(\'p\').addClass(\'bar\');

output:

<
相关标签:
6条回答
  • 2020-12-11 16:25
     (function($) {
    
        jQuery.fn.extend({
            prependClass: function(newClasses) {
                return this.each(function() {
                    var currentClasses = $(this).prop("class");
                    $(this).removeClass(currentClasses).addClass(newClasses + " " + currentClasses);
                });
            }
        });
    
    })(jQuery);
    
    0 讨论(0)
  • 2020-12-11 16:27

    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>

    0 讨论(0)
  • 2020-12-11 16:32

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

    0 讨论(0)
  • 2020-12-11 16:44

    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');
    
    0 讨论(0)
  • 2020-12-11 16:45
    function prependClass(sel, strClass) {
        var $el = jQuery(sel);
    
        /* prepend class */
        var classes = $el.attr('class');
        classes = strClass +' ' +classes;
        $el.attr('class', classes);
    }
    
    0 讨论(0)
  • 2020-12-11 16:47

    Here's another way to do it.

    $('#foo').attr('class', 'new-class ' + $('#foo').attr('class'));
    
    0 讨论(0)
提交回复
热议问题