Check if class body contains a phrase with jquery?
I know how to check if an element contains specific text, but I need to determine if a class has specific text. I have several pages where the body will have a class like:
<body class="high-school-region-1">
<body class="middle-school-region-1">
<body class="elementary-school-region-1">
So I need to target all classes that contain the phrase "region-1". Something like that:
if ($('body').hasClass('region-1')) { // do this }
But instead of hasClass it will be more like "classContains" which I know is not real, but ... is there a way to do this?
Or a better way? I don't really have an easy way to inject "region-1" as my own class on each of these pages, so it seemed like this was the way to go.
Thank you for your help!
source to share
You can use attributes containing a selector since the class is just an attribute
if ( $('body[class*="region-1"]').length > 0 ) { ...
source to share
adeneo is correct.
if ($('body').attr('class').indexOf('region-1') >= 0)
will also work.
However, there is an easy way to "introduce area-1 as its own class".
<body class="high-school region-1">
Here body
has class attributes high-school
and region-1
. You can add multiple classes to a space-separated list. In this case the code you provided is
if ($('body').hasClass('region-1')) { // do this }
Should work fine.
This is a much cleaner solution. Examining the class name for substrings essentially results in the individual class names being concatenated into one and then pulling them back out again. Not perfect IMO.
Here's a pure JS implementation http://jsfiddle.net/0f9y4pb6/
var bodyId = document.getElementById('sexybod').className.split('-'),
lastClass = bodyId[bodyId.length - 2] +'-'+ bodyId[bodyId.length - 1];
alert(lastClass);
source to share
You can write your own tiny jQuery plugin to make it reusable, in the example below:
/**
* Plugin implementation
* use with any jQuery selector that returns 1
* returns true or false depending on whether the element contains
*
* @param {string} cssClass
* @return {Boolean|undefined}
*/
$.fn.containClass = function(cssClass) {
if(this.length > 1) {
return;
}
return $(this).attr('class').indexOf(cssClass) > -1;
};
// Example usage.
$(function() {
if($('body').containClass('region')) {
console.log('Yes it contains region here.');
}
if(!$('body').containClass('blablabla')) {
console.log('no, blablabla is not found in class.');
}
console.log($('p').containClass('askjhdas'));
});
playground at jsbin: http://jsbin.com/yoyibadado/1/edit?html,js,console
source to share