سؤال

I need to use .addCLass on an list of classes, but function classList gives me an array. .addClass doesn't work with array BUT it does work if i write multiple classes, like ('.class1, class2, class3'). Is there a way to convert the .classList array to a string which can give to .addCLass. I need to get the classList dynamically hence I can't enter them manually...

Thanks

var classList = $('#postitus').attr('class').split(/\s+/).join('.');
$(classList).addClass('active');
هل كانت مفيدة؟

المحلول

var classList = $('#postitus').attr('class').split(/\s+/);

$.each(classList,function(ind,val){
   $('.' +val).addClass('active');
} );

نصائح أخرى

.split(/\s+/).join('.') gives you "foo.bar.classes" which is not a valid selector, put a fullstop before:

$('.' + classList).addClass('active');

I would say just change your code a bit and you are sorted as

var classList = $('#postitus').attr('class').split(/\s+/).join(', .');
$('.' + classList).addClass('active');

And see in comments arunpjohny has updated fiddle for that as well, or see my fiddle

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top