Skip to main content
Changed fiddle URL
Source Link
James Newton
  • 7.2k
  • 10
  • 54
  • 129

The fiddlefiddle

The code

function hasClass(element, className) { var regex = new RegExp('\\b' + className + '\\b'); do { if (regex.exec(element.className)) { return true; } element = element.parentNode; } while (element); return false; } 

OR

function hasClass(element, className) { do { if (element.classList && element.classList.contains(className)) { return true; } element = element.parentNode; } while (element); return false; } 

The fiddle

The code

function hasClass(element, className) { var regex = new RegExp('\\b' + className + '\\b'); do { if (regex.exec(element.className)) { return true; } element = element.parentNode; } while (element); return false; } 

OR

function hasClass(element, className) { do { if (element.classList.contains(className)) { return true; } element = element.parentNode; } while (element); return false; } 

The fiddle

The code

function hasClass(element, className) { var regex = new RegExp('\\b' + className + '\\b'); do { if (regex.exec(element.className)) { return true; } element = element.parentNode; } while (element); return false; } 

OR

function hasClass(element, className) { do { if (element.classList && element.classList.contains(className)) { return true; } element = element.parentNode; } while (element); return false; } 
Added solution using classList
Source Link
James Newton
  • 7.2k
  • 10
  • 54
  • 129

The fiddle

The code

function hasClass(element, className) { var regex = new RegExp('\\b' + className + '\\b'); do { if (regex.exec(element.className)) { return true; } element = element.parentNode; } while (element); return false; } 

OR

function hasClass(element, className) { do { if (element.classList.contains(className)) { return true; } element = element.parentNode; } while (element); return false; } 

The fiddle

The code

function hasClass(element, className) { var regex = new RegExp('\\b' + className + '\\b'); do { if (regex.exec(element.className)) { return true; } element = element.parentNode; } while (element); return false; } 

The fiddle

The code

function hasClass(element, className) { var regex = new RegExp('\\b' + className + '\\b'); do { if (regex.exec(element.className)) { return true; } element = element.parentNode; } while (element); return false; } 

OR

function hasClass(element, className) { do { if (element.classList.contains(className)) { return true; } element = element.parentNode; } while (element); return false; } 
Source Link
James Newton
  • 7.2k
  • 10
  • 54
  • 129

The fiddle

The code

function hasClass(element, className) { var regex = new RegExp('\\b' + className + '\\b'); do { if (regex.exec(element.className)) { return true; } element = element.parentNode; } while (element); return false; }