3-12 Encapsulate node relational functions – Encapsulate all the element siblings of an element that the function obtains
Topic request
Thought analysis
There are two ways to think about it: ① you can find the parent node of this node, and the child nodes of all the elements that get it from this node. ② It is this node that traverses forward and backward
The test data
<div id="box">
<p>The paragraph</p>
<p>The paragraph</p>
<p id='fpara'>Paragraph fpara</p>
<p>The paragraph</p>I am text <! -- I am a comment --><p id="para">Paragraph para<span>1</span>
<span>2</span>
<span>3</span>
</p>
<p>The paragraph</p>
</div>
Copy the code
Code implementation
Use idea 2 to encapsulate the function
// Encapsulates a function that retrieves all sibling nodes of an element
function getAllElementSibling(node) {
// Define the result array
var result = [];
var o = node;
// Use the while loop to iterate over the preceding node
while(o.previousSibling ! =null) {
// If it is not a big head, use unshift() to insert it into the head of the result array
if (o.previousSibling.nodeType == 1) {
result.unshift(o.previousSibling);
}
// make o its previous node
o = o.previousSibling;
}
o = node;
// Use the while loop to iterate over the nodes after node
while(o.nextSibling ! =null) {
if (o.nextSibling.nodeType == 1) {
result.push(o.nextSibling);
}
// make o its previous node
o = o.nextSibling;
}
return result;
}
Copy the code
Note: there is a slight difference. The code written by Tea creates two empty arrays, one in front of node and one behind node, and then merges the two arrays. My method defines only one result array
Testing:
var para = document.getElementById('para');
console.log(getAllElementSibling(para));
Copy the code