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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:41:42  来源:igfitidea点击:

How to search the children of a HTMLDivElement?

javascriptdom

提问by A Question Asker

I have an HTMLDivElement, and my goal is to find a divnested 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 idyou 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 getElementByIdjust do document.getElementById(id)and since ids are uniquethat will find that single div item you wanted.

您可以使用getElementByIdjust do document.getElementById(id)and 因为 ids 是唯一的,可以找到您想要的单个 div 项目。

You can also use elem.getElementsByClassNameto select a descendant of elem by class

您还可以使用elem.getElementsByClassName按类选择 elem 的后代