If the 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 does not work. Any ideas? There are no answers to jQuery.

+6
source share
3 answers

getElementsByClassName returns a NodeList , which is an array. You can check its length to determine if elements exist with a specific class:

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

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

+3
source

I tested it. It works completely. you could make any other mistake. getElementsByClassName returns empty if no element is found with the specified class name or returns a list of elements to which the class is assigned. so you can access it using an 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> 
+2
source

Source: https://habr.com/ru/post/976414/


All Articles