如何在 JavaScript 中已经找到的 div 中获取特定类的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21296611/
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
How to get elements of specific class inside a div already found in JavaScript?
提问by Ivan
What I need is to find a div with particular id, then find any element with particular class inside it and make the first of them invisible. I have tried
我需要的是找到一个具有特定 id 的 div,然后在其中找到具有特定类的任何元素,并使它们中的第一个不可见。我努力了
var hostDivName = "theHostDivName";
var hostDiv = document.getElementsByName(hostDivName);
var theElements = hostDiv.getElementsByClassName("theClassDivName");
theElements[0].style.display = "none";
But it fails on hostDiv.getElementsByClassName("theClassDivName");
with
但它失败hostDiv.getElementsByClassName("theClassDivName");
了
Object #<NodeList> has no method 'getElementsByClassName'
error.
错误。
So what is the right way? I'd prefer using pure JavaScript (rather than jQuery or whatever) as far as this seems reasonable.
那么正确的方法是什么呢?只要这看起来合理,我更喜欢使用纯 JavaScript(而不是 jQuery 或其他)。
回答by adeneo
If it's an ID, why are you using getElementsByName
and not getElementById
如果它是一个 ID,你为什么使用getElementsByName
而不是getElementById
var hostDivName = "theHostDivName";
var hostDiv = document.getElementById(hostDivName);
var theElements = hostDiv.getElementsByClassName("theClassDivName");
theElements[0].style.display = "none";
Assuming you meant name, and not ID
假设你的意思是姓名,而不是身
var hostDiv = document.getElementsByName(hostDivName)[0];