Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  138] [ 6]  / answers: 1 / hits: 40320  / 12 Years ago, sat, june 9, 2012, 12:00:00

The problem



If the element has multiple classes then it will not match with the regular property value checking, so I'm looking for the best way to check if the object has a particular class in the element's className property.



Example



// element's classname is 'hello world helloworld'
var element = document.getElementById('element');

// this obviously fails
if(element.className == 'hello'){ ... }

// this is not good if the className is just 'helloworld' because it will match
if(element.className.indexOf('hello') != -1){ ... }


So what would be the best way to do this?



just pure javascript please


More From » dom

 Answers
34
function hasClass( elem, klass ) {
return ( + elem.className + ).indexOf( +klass+ ) > -1;
}

[#85027] Friday, June 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
havenbilliec

Total Points: 324
Total Questions: 106
Total Answers: 94

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;