Javascript 如何搜索 HTMLDivElement 的子元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8826385/
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 search the children of a HTMLDivElement?
提问by A Question Asker
I have an HTMLDivElement
, and my goal is to find a div
nested beneath this.
我有一个HTMLDivElement
,我的目标是div
在它下面找到一个嵌套的。
Ideally I'd want something like getElementById
, but that function doesn't work for HTMLDivElement
.
理想情况下,我想要类似的东西getElementById
,但该功能不适用于HTMLDivElement
.
Do I need to manually traverse the graph, or is there an easier way?
我需要手动遍历图形,还是有更简单的方法?
回答by ThinkingStiff
Demo: http://jsfiddle.net/ThinkingStiff/y9K9Y/
演示:http: //jsfiddle.net/ThinkingStiff/y9K9Y/
If the <div>
you're searching for has a class, you can use getElementsByClassName()
:
如果<div>
您正在搜索有一个类,您可以使用getElementsByClassName()
:
document.getElementById( 'parentDiv' ).getElementsByClassName( 'childDiv' )[0];
If it doesn't have a class you can use getElementsByTagName()
:
如果它没有类,您可以使用getElementsByTagName()
:
document.getElementById( 'parentDiv' ).getElementsByTagName( 'div' )[0];
And if it has an id
you can, of course, just use getElementById()
to find it no matter where it is in the DOM:
如果它有一个,id
你当然可以,getElementById()
无论它在 DOM 中的哪个位置,都可以用来找到它:
document.getElementById( 'childDiv' );
回答by Emmanuel N
//For immediate children
var children = document.getElementById('id').childNodes;
//or for all descendants
var children = document.getElementById('id').getElementsByTagName('*');
回答by Raynos
var div = ...
var divChildren = div.getElementsByTagName("div");
var divYouWant = [].filter.call(divChildren, function (el) {
return matchesSomeCondition(el);
});
Ideally, I'd want something like getElementById
理想情况下,我想要像 getElementById 这样的东西
And you can use getElementById
just do document.getElementById(id)
and since ids are uniquethat will find that single div item you wanted.
您可以使用getElementById
just do document.getElementById(id)
and 因为 ids 是唯一的,可以找到您想要的单个 div 项目。
You can also use elem.getElementsByClassName
to select a descendant of elem by class
您还可以使用elem.getElementsByClassName
按类选择 elem 的后代