访问始终从document开始。
找个对象提供各种各样的方法进行搜索或修改元素。
根本: documentElement和body
DOM的根永远是document.documentElement. 这个特殊的属性将提供路径对最外层的HTML标签进行访问。
另一个开始的起点为document.body,它代表着BODY标签。
根元素
两个入口点都是有效地。但document.body可能为null.
例如,你可以从HEAD标签访问document.body,会看到null。这是自然的,因为这时候还没有BODY。
下面的例子中,第一个alert输出为null。
<!DOCTYPE HTML> <html> <head> <script> alert("Body from HEAD: "+document.body) // null </script> </head> <body> <div>The document</div> <script> alert("Body from inside body: " + document.body) </script> </body> </html>
与此相反,document.documentElement始终可以被访问。
我们还注意到document.body不能为undefined。在DOM的世界中,"找不到元素"和"没有此元素"一直为null。
作为一个通用规则,一个元素在渲染出来之前无法进行引用。
子节点
有多种方式获取子元素。
childNodes
一个元素通过childNodes与子元素数组进行关联。
所有的节点都可以被引用,包括空白节点(除IE<9)。
<!DOCTYPE HTML> <html> <body> <div>Allowed readers:</div> <ul> <li>Bob</li> <li>Alice</li> </ul> <!-- a comment node --> <script> function go() { var childNodes = document.body.childNodes for(var i=0; i<childNodes.length; i++) { alert(childNodes[i]) } } </script> <button onclick="go()" style="width:100px">Go!</button> </body> </html>
显示画面
我们注意到SCRIPT节点也将会列出来。
在所有的浏览器中(除了IE<9,因为它们没有空白节点document.body.childNodes[1]为 UL) document.body.childNodes[1] 为DIV。
children
有时候我们跳过文本节点,只想浏览元素节点。children属性刚好提供该功能。
它包含所有的元素节点。使用上文同样的代码,但使用children替换childNodes。它将会只输出元素节点。
<!DOCTYPE HTML> <html> <body> <div>Allowed readers:</div> <ul> <li>Bob</li> <li>Alice</li> </ul> <!-- a comment node --> <script> function go() { var children = document.body.children for(var i=0; i<children.length; i++) { alert(children[i]) } } </script> <button onclick="go()" style="width:100px">Go!</button> </body> </html>
当IE<9时'children'的注释节点
当IE版本小于9时children也会列出注释节点。
子链接
我们还可以使用siblings, parent等等来进一步方便遍历元素。
firstChild和lastChild
通过 firstChild 和 lastChild 我们可以很方便的访问元素的第一个节点和最后一个节点。
子节点
var body = document.body
alert(body.firstChild === body.childNodes[0])
alert(body.lastChild === body.childNodes[body.childNodes.length-1])
parentNode, previousSibling 和 nextSibling
parentNode将会引用父节点,当document.documentElement 调用时返回null。
通过previousSibling 和 nextSibling 访问左右相邻节点。
<!DOCTYPE HTML> <html> <head> <title>My page</title> </head> <body> <div>The header</div> <ul><li>A list</li></ul> <div>The footer</div> </body> </html>
让我们使用图片对上面的文档结构进行说明。
相邻节点
浏览器始终维持着正确的节点间的链接关系。可以更改DOM, 添加/删除元素,但我们没有必要手动修改节点间的链接关系,因为浏览器已经做了。
思考
document.body.lastChild.nextSibling是否始终为null
document.body.children[0].previousSibling是否始终为null
总结
DOM树紧密的连接在一起:
向上
parentNode
向下
children/childNodes, firstChild, lastChild
左右
previousSibling/nextSibling
浏览器保证了这些链接是准确的,它们都是只读的。
如果没有这种节点(子,父,邻居),将返回null。
转载于:https://blog.51cto.com/skpark/1615040