-1

I want to check if an element has a class specified or not (without knowing the class). For example, given:

<div id="ball" class="dd">

and:

<div id="ball">

I want to check if it has no class at all.

I know there is a function called hasClass but this requires the class name to work.

EDIT

The question was answered in that other post. The answer which I found most useful was this:

$("#mydiv").prop('classList').length
Community
  • 1
  • 1
Thomas Williams
  • 1,528
  • 1
  • 18
  • 37

4 Answers4

3

If you wanna check if the element has any class at all, you can check using the .attr() property:

$(element).attr("class").trim().length == 0

This handles a case like this too:

<div class=""></div>

You can also try to create a hasAttr() function this way:

var attr = $(this).attr('name');

// For some browsers, `attr` is undefined; for others, `attr` is false. Check for both.
if (typeof attr !== typeof undefined && attr !== false) {
  // Element has this attribute
}

More information about creating .hasAttr() at A jQuery hasAttr() Equivalent.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • I tried $(element).attr("class").trim().length==0 but kept getting the error TypeError: S()attrr is undefined. So that doesn't work if you have no class at all. – Thomas Williams Feb 03 '16 at 13:35
  • @ThomasWilliams Did you see the second one, which has `hasAttr()` and stuff? You need to use the `typeof` code for checking `undefined`. Try it out. – Praveen Kumar Purushothaman Feb 03 '16 at 13:45
2

One possible approach (if you consider elements with empty classes - like <div class=""></div> - as classful elements):

$('#ball').is('[class]');

It's more direct than checking class attribute value. In fact, you don't even need jQuery to do this:

document.getElementById('ball').hasAttribute('class');

Yet another option is using classList. This API is tremendously useful (however, it's not supported in IE9-). classList returns DOMTokenList, an array-like object; the point is, if the class attribute was not set or is empty, its length is 0:

document.getElementById('ball').classList.length === 0;
raina77ow
  • 103,633
  • 15
  • 192
  • 229
0

Try this :

<div id="ball" class="dd">
<div id="ball">

if ($('div').attr('class') != undefined){
        alert('YES');
    }
Monty
  • 1,110
  • 7
  • 15
0

Try this

var attr = $(this).attr('class');
if (typeof attr !== typeof undefined && attr !== false) {

}
Amarnath
  • 62
  • 4