This article analyzes the node relationship of Javascript with examples. Share it with everyone for your reference. The details are as follows:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>节点关系</title> <script type="text/javascript"> function Demo() { var divObj = document.getElementById("divDemo"); //获取父节点 var parentNode = divObj.parentNode; //displayNodeInfo(parentNode); //获取子节点 var childNodes = divObj.childNodes; //子节点返回的是一个集合,即数组 //alert(childNodes.length); //显示节点个数 //displayNodeInfo(childNodes[0]); //获取兄弟节点 //----------获取上一个兄弟节点 var preBrotherNode = divObj.previousSibling.previousSibling; //标签之间存在空行时,会出现一个空白的文本节点,在获取节点时,一定要注意。 //displayNodeInfo(preBrotherNode); //----------获取下一个兄弟节点 var nextBrotherNode = divObj.nextSibling; displayNodeInfo(nextBrotherNode); } function displayNodeInfo(node) { alert("Name:" + node.nodeName + ",Type:" + node.nodeType + ",Value:" + node.nodeValue); } </script> </head> <body> <input type="button" value="测试" onclick="Demo()" /> <div id="divDemo">div内容</div> <table> <tr> <td>单元格1</td> <td>单元格2</td> </tr> <tr> <td>单元格3</td> <td>单元格4</td> </tr> </table> </body> </html>
I hope this article will be helpful to everyone’s JavaScript programming design.