Detecting if any element has any class in jQuery
I inherited some jQuery and HTML and have to figure out if any of the HTML elements have a class name of any value. I have read several threads and Googled but cannot find anything useful. So in pseudocode, I want:
Loop through all HTML elements
If any of them have any class at all:
Get their class name as a string
Hope this makes sense!
source to share
What is it worth for:
$(this).hasClass()
always returns false.
$("[class]")
doesn't work either as it returns items like
<p class=""> my p </p>
jsfiddle for both here: http://jsfiddle.net/JZ8LV/1/
Decision
$(this).hasClass('')
returns true for elements without a class, including forms
<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 tags with the corresponding class .
Jsfiddle: http://jsfiddle.net/2Rtj5/
source to share
You can use something like this:
$("[class]").each(function(){
var className = $(this).attr("class");
})
Demo: http://jsfiddle.net/L5WAV/1/ (see results in console - need to find two divs)
source to share
var classObj = {};
$('*').each(function(){
var cNames = this.className.split(' ');
for(var i=0, l=cNames.length; i<l; i+=1){
classObj[cNames[i]] = true;
}
});
This will give you an object ( classObj
) with every seeming document class as a property, so the class name will not appear multiple times if there are elements with the same class in the document. I really wouldn't do it or see a use case in it.
source to share
Not a direct question, but I need it, so it's appropriate for future users.
If you want to find if any element has a specific class, you can use this function:
function find_any_element(className) {
var found = false;
$('*').each(function() {
if ($(this).hasClass(className)) {
var class_name = $(this).attr('class');
alert("There is an element with this class: " + class_name);
found = true;
}
});
if(!found) {
alert("No element with className '" + className + "' found.");
}
}
source to share