jquery addClass() to first position of multiple classes

匿名 (未验证) 提交于 2019-12-03 00:48:01

问题:

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.

回答1:

function prependClass(sel, strClass) {     var $el = jQuery(sel);      /* prepend class */     var classes = $el.attr('class');     classes = strClass +' ' +classes;     $el.attr('class', classes); } 


回答2:

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


回答3:

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


回答4:

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



回答5:

Here's another way to do it.

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!