If class exists, do something with Javascript

getElementsByClassName returns a NodeList. It will never be null. It might have a .length of 0.


getElementsByClassName returns a NodeList which is an array-like object. You can check its length to determine if elements with defined class exist:

var isMobileVersion = document.getElementsByClassName('snake--mobile');
if (isMobileVersion.length > 0) {
    // elements with class "snake--mobile" exist
}

Here is very sample solution for check class (hasClass) in Javascript:

const mydivclass = document.querySelector('.mydivclass');
// if 'hasClass' is exist on 'mydivclass'
if(mydivclass.classList.contains('hasClass')) {
    // do something if 'hasClass' is exist.
}

I have tested it. its completely working . you might done any other mistake. getElementsByClassName return empty if no element found with given class name or return list of elements that have given class. so you can access it using index.

var isMobileVersion = document.getElementsByClassName('snake--mobile');
if (isMobileVersion.length > 0) {
  isMobileVersion[0].style.color="red";
  alert('class exist');
}
<div id="snake" class="snake--mobile">Class Exist div </div>