Reputation: 1606
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.
Upvotes: 52
Views: 156070
Reputation: 341
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.
}
Upvotes: 16
Reputation: 543
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
Upvotes: 0
Reputation: 9
var id=$("#main .slides .gallery-cell.is-selected").attr('id');
var isselected = document.getElementById(id);
isselected.scrollIntoView({behavior: "smooth", block: "center", inline: "center"});
Upvotes: -1
Reputation: 2412
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>
Upvotes: 5
Reputation: 943193
getElementsByClassName
returns a NodeList. It will never be null
. It might have a .length
of 0
.
Upvotes: 6
Reputation: 145378
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
}
Upvotes: 79