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

Author: hardsky, 2015-12-04

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.

 12
Author: Grundy, 2015-12-08 10:34:12

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

 2
Author: tutankhamun, 2015-12-04 11:58:04

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

 2
Author: voronovam, 2015-12-11 04:39:39

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

 0
Author: Дмитрий Бабанин, 2020-01-27 08:24:26