JavaScript 通过 className 获取子元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8337900/
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
JavaScript get child elements by className
提问by ghanshyam.mirani
I have written the following line in Javascript:
我在 Javascript 中编写了以下行:
var eleCategory = document.getElementById("cmbCategory");
Now I want to find all elementbyClassName
contained in the eleCategory
element.
现在我想找到elementbyClassName
包含在eleCategory
元素中的所有内容。
Is it possible with something like this?
这样的事情有可能吗?
var eleChild = eleCategory.getElementByClassName("autoDropdown");
How can I get the child element of the parent element?
如何获取父元素的子元素?
采纳答案by canon
getElementsByClassName
hasn't been implemented in all browsers. Niels' solution, for instance, doesn't work in IE. However, others have created their own implementation; John Resig has a write-up on his blog
getElementsByClassName
尚未在所有浏览器中实现。例如,Niels 的解决方案在 IE 中不起作用。但是,其他人已经创建了自己的实现;John Resig 在他的博客上写了一篇文章
回答by Niels
Yes it is possible, see this fiddle: http://jsfiddle.net/ajAY2/
是的,有可能,请参阅此小提琴:http: //jsfiddle.net/ajAY2/
But the getElementsByClassName
will return a collection of elements, because it will look for all classes within the object. So if you only got 1 class like that within this object, you have to get the 0th object like:
但是getElementsByClassName
将返回元素的集合,因为它将查找对象内的所有类。所以如果你在这个对象中只有 1 个这样的类,你必须得到第 0 个对象,如:
var eleChild = eleCategory.getElementsByClassName("autoDropdown")[0];
Total script:
总脚本:
Script:
脚本:
var eleCategory = document.getElementById("cmbCategory");
var eleChild = eleCategory.getElementsByClassName("autoDropdown");
alert(eleChild.length);
HTML
HTML
<div id="cmbCategory">
<div class="autoDropdown"></div>
<div class="autoDropdown"></div>
</div>
<div class="autoDropdown"></div>
回答by Michael Sazonov
var eleChild = eleCategory.childNodes;
for( i = 0 , j = eleChild.length; i < j ; i++ ){
if( eleChild[ i ].className == "autodropdown" ){
YOUr_SCRIPT
}
}
回答by Katu
You can access everything in DOM tree, with this:
您可以通过以下方式访问 DOM 树中的所有内容:
document.childNodes[0].childNodes[0].childNodes[0] ... n[n] ...
Just look for childnodes of childnodes. And if I remember right, you can:
只需查找子节点的子节点。如果我没记错的话,你可以:
var element = document.getElementById("myid");
var child = element.childNode[0]
回答by Reggie Pinkham
The modern way:
现代方式:
var element = document.querySelector('#Element');
var elementChildren = element.querySelectorAll('.Element-child');
elementChildren
will contain an array of all children with a class of Element-child
within element
.
elementChildren
将包含一个包含类Element-child
内的所有子项的数组element
。
Using bracket notation we could access the nth child in our array, e.g.
使用括号表示法,我们可以访问数组中的第 n 个孩子,例如
var firstElementChild = elementChildren[0]; // zero-based