Get the previous node
In Javascript, get the previous node through previousSibling.
Syntax:
nodeObject.previousSibling
Among them, nodeObject is the node object (element node).
Under IE, blank nodes (spaces, carriage returns, and Tab keys) between nodes will be ignored; under browsers that follow W3C specifications (Chrome, FireFox, Safari, etc.), they will not be ignored.
Please look at the following piece of code:
<div id="demo"> <div name="preNode">上一个节点</div> <div id="thisNode">当前节点</div> <div name="nextNode">下一个节点</div> </div> <script type="text/javascript"> document.getElementById("thisNode").onclick=function(){ var preNode=this.previousSibling; alert( "上一个节点的类型是:"+preNode.nodeType+"\n"+ (preNode.nodeType==1?"上一个节点的名称是:"+preNode.getAttribute("name"):"") ); } </script>
Example demonstration:
Under IE8.0 and below, display:
The type of the previous node Is: 1
The name of the previous node is: preNode
Under Chrome, Opera, Safari, FireFox, it displays:
The type of the previous node is: 3
For the above code Make slight modifications to remove the spaces between nodes:
<div id="demo"><div name="preNode">上一个节点</div><div id="thisNode">当前节点</div><div name="nextNode">下一个节点</div></div> <script type="text/javascript"> document.getElementById("thisNode").onclick=function(){ var preNode=this.previousSibling; alert( "上一个节点的类型是:"+preNode.nodeType+"\n"+ (preNode.nodeType==1?"上一个节点的名称是:"+preNode.getAttribute("name"):"") ); } </script>
Example demonstration:
Top The type of a node is: 1
The name of the previous node is: preNode
Get the next node
In Javascript, you can use nextSibling to get the next node.
Same as previousSibling, under IE, nextSibling will also ignore blank nodes (spaces, carriage returns and Tab keys) between nodes; under browsers that follow W3C specifications (Chrome, FireFox, Safari, etc.) Won't.