Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  178] [ 7]  / answers: 1 / hits: 59415  / 14 Years ago, tue, november 23, 2010, 12:00:00

How can I check in JavaScript if a DOM element contains a class?



I tried the following code, but for some reason it doesn't work...



if (document.getElementById('element').class == class_one) {
//code...
}

More From » html

 Answers
8

To get the whole value of the class atribute, use .className



From MDC:




className gets and sets the value of the class attribute of the specified element.




Since 2013, you get an extra helping hand.



Many years ago, when this question was first answered, .className was the only real solution in pure JavaScript. Since 2013, all browsers support .classList interface.



JavaScript:



if(document.getElementById('element').classList.contains(class_one)) {
//code...
}


You can also do fun things with classList, like .toggle(), .add() and .remove().



MDN documentation.



Backwards compatible code:



if(document.getElementById('element').className.split( ).indexOf(class_one) >= 0) {
//code...
}

[#94868] Saturday, November 20, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isham

Total Points: 69
Total Questions: 86
Total Answers: 86

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;