49

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.

Avatar
  • 14,622
  • 9
  • 119
  • 198
Alex
  • 1,576
  • 3
  • 17
  • 35

6 Answers6

74

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
}
VisioN
  • 143,310
  • 32
  • 282
  • 281
13

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.
}
kalucki23
  • 172
  • 4
  • 15
  • Yup, "contains" is the way to go here... ex. `if( document.getElementById("MyElement").classList.contains('special-class') ) { console.log('Found!') }` – Paul Brady Oct 15 '21 at 21:35
  • Thanks a lot `querySelector` solved the problem now I got `null` if the class isn't existing. – Salem May 29 '22 at 20:35
  • This should definitely be the accepted answer. – henxdl May 02 '23 at 14:04
6

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • @Salem — Umm. Yes? So `getElementsByClassName` *doesn't* return `null` and `[0]` is `undefined` because it has a `length` of `0` … just like this answer says. – Quentin May 29 '22 at 20:34
5

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>
Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40
  • **You are wrong.** `getElementsByClassName` never returns `null`. In your example you check the result for being not `null`, which will always be `true`, as `NodeList` object is not falsy. Try checking against "class *not* exist" and you will see. – VisioN Oct 20 '15 at 07:46
  • i have checked my example. it will return empty object if class not found. thanx @VisioN for correcting my mistake – Krupesh Kotecha Oct 20 '15 at 09:02
  • Nevertheless, your update didn't fix the problem, as `if (x)` will still check for `true` value. The only way to assess if elements exist is to compare `length` property with `0`, as was described in the other answers. – VisioN Oct 20 '15 at 09:11
0

querySelector() method from document returns the first Element that matches the specified selector otherwise returns null if there is no match query selector reference.

 Syntax
 element = document.querySelector(selectors);

console.log(`existing-class element ${document.querySelector('.existing-class')}`)

console.log(`non-existing-class element ${document.querySelector('.non-existing-class')}`)

if(document.querySelector('.existing-class')) {
  alert('inside if block')
}
<div class="existing-class">

explicit null check with if statement is not required, since null is a falsey value when encountered in a boolean context, using the output of querySelector will work falsey reference

sagar buddhi
  • 493
  • 5
  • 8
-1
var id=$("#main .slides .gallery-cell.is-selected").attr('id');
var isselected = document.getElementById(id);
isselected.scrollIntoView({behavior: "smooth", block: "center", inline: "center"});
sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40
  • 2
    From Review:  Hi, please don't answer just with source code. Try to provide a nice description about how your solution works. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). Thanks – sɐunıɔןɐqɐp Dec 11 '19 at 10:51