you would imagine this would be easy to implement, but oh well..
anyway, I have an element to which classes are added or removed based of interaction on the site.
<You don't need jQuery to achive this.
var hasNoClass = !document.getElementById("#id").className;
if(hasNoClass){ /*...*/ }else{ /*...*/ }
Same approach using jQuery
var hasNoClass = !$("#id").className;
if(hasNoClass){ /*...*/ }else{ /*...*/ }
See working code snippet below:
var elemClasses = $('body').attr('class') ? $('body').attr('class').split(/\s+/) : [];
if (elemClasses.length == 1){
alert('Only one class');
}
else{
alert('Element has ' + elemClasses.length + ' clases');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class=""></body>
Use this one...
var classes = $('#mydiv').attr('class').split(/\s+/);
This will give you an array of all the classes applied to your element. For the length you can simply extend it as
var classes = $('#mydiv').attr('class').split(/\s+/).length;
Cheers
In jQuery:
if($("#mydiv").is('[class]')
As YoYo points it out in comment, this would failed if attribute class as an empty string set. So don't use it...
Use classList
property on the HTML Element:
document.getElementById("mydiv").classList.length
document.querySelector("#mydiv").classList.length
$("#mydiv").prop('classList').length // jQuery method.
The classList
gives the array of classes present for the element. So, .length
will say if there's any class there.
Check the classList
property:
$("#mydiv").prop('classList').length
Or, with the DOM:
document.querySelector('#mydiv').classList.length
If the length is zero it has no classes, if it's greater than zero it has that number of classes.
With the DOM as a function:
// a named function to take a DOM node:
function hasClasses(node) {
// returns a Boolean, true if the length
// of the Array-like Element.classList is
// greater than 0, false otherwise:
return node.classList.length > 0;
}
var elem = document.getElementById('mydiv');
if (hasClasses(elem)) {
elem.classList.add('found');
}
function hasClasses(node) {
return node.classList.length > 0;
}
var elem1 = document.getElementById('mydiv'),
elem2 = document.getElementById('myotherdiv');
if (hasClasses(elem1)) {
elem1.classList.add('found');
}
if (hasClasses(elem2)) {
elem2.classList.add('found');
}
div {
height: 2em;
border: 3px solid limegreen;
margin-top: 0.5em;
border-radius: 1em 0;
}
.found {
border-color: orange;
}
<div id="mydiv" class="hasAClass"></div>
<div id="myotherdiv"></div>
JS Fiddle demo.
In the event of a browser that doesn't feature the element.classList
interface, you could instead use className
:
// retrieving the specified element,
// retrieving its 'className' property,
// removing the leading and trailing white-space,
// retrieving the length of the trimmed string,
// checking that this length is greater than 0:
$("#mydiv").prop('className').trim().length > 0;
var div1 = $("#mydiv"),
div2 = $('#myotherdiv'),
div1HasClassName = div1.prop('className').trim().length > 0,
div2HasClassName = div2.prop('className').trim().length > 0;
// Boolean true:
if (div1HasClassName) {
div1.addClass('found');
}
// Boolean false:
if (div2HasClassName.length > 0) {
div2.addClass('found');
}
div {
height: 2em;
border: 3px solid limegreen;
margin-top: 0.5em;
border-radius: 1em 0;
}
.found {
border-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv" class="a"></div>
<div id="myotherdiv"></div>
JS Fiddle demo.
Or, with the DOM:
// retrieving the element with the id of 'mydiv'
// (or null if no such element exists),
// retrieving the className, as a String, of the element,
// removing the leading and trailing white-space,
// retrieving the length of the String,
// evaluating whether the length is greater than 0;
// returning a Boolean true if so, false if not:
document.querySelector("#mydiv").className.trim().length > 0;
var div1 = document.querySelector("#mydiv"),
div2 = document.querySelector('#myotherdiv'),
div1HasClassName = div1.className.trim().length > 0,
div2HasClassName = div2.className.trim().length > 0;
// Boolean true:
if (div1HasClassName) {
div1.className += ' found';
}
// Boolean false:
if (div2HasClassName) {
div2.className += ' found';
}
div {
height: 2em;
border: 3px solid limegreen;
margin-top: 0.5em;
border-radius: 1em 0;
}
.found {
border-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv" class="a"></div>
<div id="myotherdiv"></div>
JS Fiddle demo.
It's also possible to write a (very) simple jQuery selector to select only those elements that have classes, this selector takes no arguments:
// defining the selector-name 'hasClasses':
$.expr[':'].hasClasses = function(
// this is the current element of the collection over
// which the selector iterates:
objNode
) {
// here we return true, if:
// the current node has a 'class' attribute, and
// has a classList (though this could be substituted
// for className for backwards compatibility), and
// the classList.length is greater than zero
// Otherwise returning false:
return objNode.hasAttribute('class') && objNode.classList && objNode.classList.length > 0;
};
$('div:hasClasses').addClass('found');
$.expr[':'].hasClasses = function(
objNode
) {
return objNode.hasAttribute('class') && objNode.classList && objNode.classList.length > 0;
};
$('div:hasClasses').addClass('found');
div {
height: 2em;
border: 3px solid limegreen;
margin-top: 0.5em;
border-radius: 1em 0;
}
.found {
border-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class></div>
<div class="hasAClass"></div>
<div class=""></div>
<div></div>
<div class="hasAClass"></div>
JS Fiddle demo.
Or, similarly, a jQuery plugin that also takes no arguments:
// using an immediately-invoked function expression (IIFE),
// to immediately run the function as soon as it's encountered:
(function($) {
// defining the plugin name ('hasClasses'):
$.fn.hasClasses = function() {
// 'this', here, is the jQuery collection
// over which we're iterating with filter():
return this.filter(function() {
// we're using this node potentially three times,
// so we cache it here for simplicity ('this,' within
// the filter() method, is the DOM node):
var objNode = this;
// if the following assessment returns true the
// current node is retained in the collection and
// and retained for chaining, if it evaluates to
// false it's discarded from the collection and so
// not retained/returned:
return objNode.hasAttribute('class') && objNode.classList && objNode.classList.length > 0;
});
};
// passing in jQuery to allow the use of the $ alias
// within the IIFE:
})(jQuery);
// calling the plugin:
$('div').hasClasses().addClass('found');
(function($) {
$.fn.hasClasses = function() {
return this.filter(function() {
var objNode = this;
return objNode.hasAttribute('class') && objNode.classList && objNode.classList.length > 0;
});
};
})(jQuery);
$('div').hasClasses().addClass('found');
div {
height: 2em;
border: 3px solid limegreen;
margin-top: 0.5em;
border-radius: 1em 0;
}
.found {
border-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class></div>
<div class="hasAClass"></div>
<div class=""></div>
<div></div>
<div class="hasAClass"></div>
JS Fiddle demo.