LBF
LBF

Reputation: 1205

Check if a body class contains a phrase with jquery?

I know how to check if an element contains certain text, but I need to determine if a class has certain 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 this:

 if ($('body').hasClass('region-1')) { // do this }

But instead of hasClass, it would be more like "classContains" - which I know is not a real thing, but... is there a way to do that?

Or a better way? I don't really have an easy way to inject "region-1" as its own class on each of those pages, so it seemed like this was the way to go.

Thanks for your help!

Upvotes: 4

Views: 7955

Answers (4)

filype
filype

Reputation: 8380

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'));
});

play area on jsbin: http://jsbin.com/yoyibadado/1/edit?html,js,console

Upvotes: 0

user2537690
user2537690

Reputation:

adeneo is correct.

if ($('body').attr('class').indexOf('region-1') >= 0) would also work.

However, there is an easy way to "inject region-1 as its own class".

<body class="high-school region-1">

Here, the body has both high-school and region-1 class attributes. You can add multiple classes as a space-separated list. In this case, the code you presented

if ($('body').hasClass('region-1')) { // do this }

Should work just fine.

This is a much cleaner solution. Examining a class name for substrings is essentially putting separate class names into one, then pulling them back out again later. Not ideal IMO.

Upvotes: 4

Hunter Frazier
Hunter Frazier

Reputation: 477

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);

Upvotes: 1

adeneo
adeneo

Reputation: 318232

You can use the attributes contains selector, as the class is just an attribute

if ( $('body[class*="region-1"]').length > 0 ) { ...

Upvotes: 9

Related Questions