Check for a CSS class in javascript
How do I check whether an element has a class or not in pure javascript?
You need to add a class to the element on click, but check whether it has this class before adding it, so that the class is not duplicated.
Here is the code:
var cells = document.getElementsByTagName('td');
for(var i=0; i<cells.length;i++){
cells[i].addEventListener('click', selectDate);
}
function selectDate(){
this.className += ' active';
}
Link to the full code jsfiddle
4 answers
The method will help youclassList.contains
instead of className
Contains ( String )
Checks whether the element has this class (returns true or false)
You can use it like this:
if(this.classList.contains('active'))
Where this should be an html element.
You can use the following function:
function hasClass(element, className) {
var rx = new RegExp('(?:^| )' + className + '(?: |$)');
return rx.test(element.className);
}
Plus, this solution works even on ancient browsers
I did this: a class is added on a click and deleted on a second click. here is the code:
var cells = document.getElementsByTagName('td');
for(var i=0; i<cells.length;i++){
cells[i].addEventListener('click', selectDate);
}
function selectDate(){
if(this.classList.contains('active')){
this.classList.remove('active');
}else {
this.classList.add('active');
}
}
Link to the full code: jsfiddle
If you need to check exactly the presence of a class, then use the following construction
!!~elem.getAttribute("class").indexOf("my__class")
Method:
classList.toggle('active')
Adds a class if it is not present and deletes it if it is present.
Method:
parent.contains(child)
Returns true if parent contains child or parent == child That is, if we have several children, then we will have to check in a loop. And again, nesting