Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

javascript - How to get all CSS classes of an element?

I have an element with multiple classes and I'd like to get its css classes in an array. How would I do this? Something like this:

var classList = $(this).allTheClasses();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No need to use jQuery for it:

var classList = this.className.split(' ')

If you for some reason want to do it from a jQuery object, those two solutions work, too:

var classList = $(this)[0].className.split(' ')
var classList = $(this).prop('className').split(' ')

Of course you could switch to overkill development mode and write a jQuery plugin for it:

$.fn.allTheClasses = function() {
    return this[0].className.split(' ');
}

Then $(this).allTheClasses() would give you an array containing the class names.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...