53

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.

3

6 Answers 6

79

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

I got this Cannot read properties of undefined (reading 'length'
16

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.
}

2 Comments

Yup, "contains" is the way to go here... ex. if( document.getElementById("MyElement").classList.contains('special-class') ) { console.log('Found!') }
Thanks a lot querySelector solved the problem now I got null if the class isn't existing.
6

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

1 Comment

@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.
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>

3 Comments

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.
i have checked my example. it will return empty object if class not found. thanx @VisioN for correcting my mistake
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.
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

Comments

-1
var id=$("#main .slides .gallery-cell.is-selected").attr('id');
var isselected = document.getElementById(id);
isselected.scrollIntoView({behavior: "smooth", block: "center", inline: "center"});

1 Comment

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?. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.