如果类存在,用 Javascript 做一些事情
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26254957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
If class exists, do something with Javascript
提问by Alex
I have a class and if it exists, I want to use the variable as a true/false if statement.
我有一个类,如果它存在,我想将该变量用作 true/false if 语句。
HTML
HTML
<div id="snake" class="snake--mobile">
JS
JS
var isMobileVersion = document.getElementsByClassName('snake--mobile');
if (isMobileVersion !== null)
alert('xx');
However, it's not working. Any ideas? No jQuery answers, please.
但是,它不起作用。有任何想法吗?没有 jQuery 答案,请。
回答by VisioN
getElementsByClassNamereturns a NodeListwhich is an array-like object. You can check its lengthto determine if elements with defined class exist:
getElementsByClassName返回NodeList其是阵列状物体。您可以检查它length以确定是否存在具有定义类的元素:
var isMobileVersion = document.getElementsByClassName('snake--mobile');
if (isMobileVersion.length > 0) {
// elements with class "snake--mobile" exist
}
回答by Quentin
getElementsByClassNamereturns a NodeList. It will never be null. It might have a .lengthof 0.
getElementsByClassName返回一个节点列表。它永远不会null。它可能有一个.length的0。
回答by Krupesh Kotecha
I have tested it. its completely working . you might done any other mistake. getElementsByClassNamereturn emptyif no element found with given class name or return list of elements that have given class. so you can access it using index.
我已经测试过了。它完全正常工作。你可能犯了任何其他错误。如果没有找到具有给定类名的元素或返回具有给定类的元素列表,则getElementsByClassName返回空。所以你可以使用索引访问它。
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>
回答by Md Sabbul Ansari
var id=$("#main .slides .gallery-cell.is-selected").attr('id');
var isselected = document.getElementById(id);
isselected.scrollIntoView({behavior: "smooth", block: "center", inline: "center"});
回答by sagar buddhi
querySelector()method from document returns the first Element that matches the specified selector otherwise returns nullif there is no match query selector reference.
文档中的querySelector()方法返回与指定选择器匹配的第一个元素,否则如果没有匹配的查询选择器引用,则返回null。
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
不需要使用 if 语句进行显式 null 检查,因为 null 在布尔上下文中是一个假值,使用 querySelector 的输出将工作假引用

