I have a simple if statement as such:
if ($(\'html\').hasClass(\'m320\')) {
// do stuff
}
This works as expected. However, I want to add
The hasClass method will accept an array of class names as an argument, you can do something like this:
$(document).ready(function() {
function filterFilesList() {
var rows = $('.file-row');
var checked = $("#filterControls :checkbox:checked");
if (checked.length) {
var criteriaCollection = [];
checked.each(function() {
criteriaCollection.push($(this).val());
});
rows.each(function() {
var row = $(this);
var rowMatch = row.hasClass(criteriaCollection);
if (rowMatch) {
row.show();
} else {
row.hide(200);
}
});
} else {
rows.each(function() {
$(this).show();
});
}
}
$("#filterControls :checkbox").click(filterFilesList);
filterFilesList();
});
You just had some messed up parentheses in your 2nd attempt.
var $html = $("html");
if ($html.hasClass('m320') || $html.hasClass('m768')) {
// do stuff
}
For anyone wondering about some of the different performance aspects with all of these different options, I've created a jsperf case here: jsperf
In short, using element.hasClass('class')
is the fastest.
Next best bet is using elem.hasClass('classA') || elem.hasClass('classB')
. A note on this one: order matters! If the class 'classA' is more likely to be found, list it first! OR condition statements return as soon as one of them is met.
The worst performance by far was using element.is('.class')
.
Also listed in the jsperf is CyberMonk's function, and Kolja's solution.
This is in case you need both classes present. For either or logic just use ||
$('el').hasClass('first-class') || $('el').hasClass('second-class')
Feel free to optimize as needed