简体   繁体   English

DOM 访问不同的元素

[英]DOM access to different elements

I'm trying to learn how to get to different levels of the DOM with javaScript, once I've made an initial entry point.一旦我建立了初始入口点,我正在尝试学习如何使用 javaScript 到达不同级别的 DOM。 For example, if I want to access the following div element, I would target its attribute:例如,如果我想访问以下 div 元素,我将定位其属性:

var divContent =  document.getElementById(‘box_1’);

How would I access the li tags?我将如何访问 li 标签? Ultimately, I want to write an event handler that will populate the li tags, but I first need to know how to access them via the ID attribute for the div.最终,我想编写一个事件处理程序来填充 li 标签,但我首先需要知道如何通过 div 的 ID 属性访问它们。

<div id="box_1">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>

Guess what: you can get the elements by TagName , having your id as the parent node.猜猜看:您可以通过TagName获取元素,将您的 id 作为父节点。 Cool, han?酷,韩?

var parent = document.getElementById('box_1'),
    children = parent.getElementsByTagName('li');
    // gets all children of parent

Now you just need to iterate over child 'li' nodes现在您只需要遍历子“li”节点

var i, e;
for (i = 0; i < children.length; ++i) {
    e = children[i];
    //do magic with e
}

您是否试图获取某个父级的所有li元素?

children = document.querySelectorAll('#box_1 li');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM