If class exists, do something with Javascript

I have a class and if it exists, I want to use the variable as a true/false if statement.

HTML

<div id="snake" class="snake--mobile">

JS

var isMobileVersion = document.getElementsByClassName('snake--mobile');
if (isMobileVersion !== null)
  alert('xx');

However, it’s not working. Any ideas? No jQuery answers, please.

Answer

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
}

Leave a Reply

Your email address will not be published. Required fields are marked *