Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 664
Alex Avatar asked Oct 08 '14 10:10

Alex


1 Answers

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 } 
like image 128
VisioN Avatar answered Sep 21 '22 04:09

VisioN