Discovering if any element has any class in jQuery
Solution 1
Try:
$('*').each(function() {
if ($(this).hasClass()) {
var class_name = $(this).attr('class');
// do something
}
});
Why you would want to do this, I have no idea. It is very inefficient
Solution 2
For what it's worth:
$(this).hasClass()
always returns false.
$("[class]")
doesn't work either, as it returns elements like
<p class=""> my p </p>
jsfiddle for both here: http://jsfiddle.net/JZ8LV/1/
Solution:
$(this).hasClass('')
returns true for elements without a class, including those of the form
<p class=""> my p </p>
so
$('*').each(function() {
if ($(this).hasClass('') === false) {
$("body").append($(this).prop("tagName") + " has a proper class defined <br/>");
}
});
returns all the tags with a proper class defined.
Jsfiddle: http://jsfiddle.net/2Rtj5/
Solution 3
You can use something like this:
$("[class]").each(function(){
var className = $(this).attr("class");
})
Demo: http://jsfiddle.net/L5WAV/1/ (see results in console - two divs should be found)
Solution 4
To get all elements with class you can use $('*[class]')
:
$('*[class]').each(function(){
// do what you want
});
You can even easily count them with $('*[class]').length
.
Solution 5
var classObj = {};
$('*').each(function(){
var cNames = this.className.split(' ');
for(var i=0, l=cNames.length; i<l; i+=1){
classObj[cNames[i]] = true;
}
});
That would give you an Object (classObj
) with every appearing class of the document as property, so a class name won't show up multiple times if there are elements with the same class in the document. I really would not do this or see any use-case in this though.
Kev
Updated on July 09, 2022Comments
-
Kev almost 2 years
I have inherited some jQuery and HTML and need to find out if any of the HTML elements have a class name of any value. I've read around a few threads and Googled but can't find anything useful. So in pseudo-code what I'd like is:
Loop through all HTML elements If any of them have any class at all: Get their class name as a string
Hoping that makes sense!
-
isherwood over 11 yearsYeah, it's a pretty heavy operation. I'd bet that there's a better approach to the problem.
-
Kev over 11 yearsThank you :) its not something I want to do particularly. I'm no jQuery expert, but with the code I've inherited I think its maybe the only way to do what I need and the client (who fancies himself a talented amateur coder) wants. I have managed to strip the number of classes down to 6 so I'm hoping that will reduce overhead. Thanks again, I appreciate it.
-
Kev over 11 yearsThank you too for your time, I appreciate it :)
-
Kev over 11 yearsThanks for your time also, I do appreciate it :)
-
Kev over 11 yearsThanks for your time, I appreciate it :)
-
Cris about 6 yearsreasonably efficient if $('*') selector is other than ' * '
-
Shahbaz A. almost 6 yearsMan. You are great.