使用原生js实现给定节点的父节点下所有子节点的元素
function getSiblings(node) {
// Handle cases where the node is null or doesn't have a parent
if (!node || !node.parentNode) {
return [];
}
const parent = node.parentNode;
const siblings = [];
// Iterate through the parent's children and add them to the siblings array,
// excluding the provided node itself.
for (let i = 0; i < parent.children.length; i++) {
if (parent.children[i] !== node) {
siblings.push(parent.children[i]);
}
}
return siblings;
}
// Example usage:
// Assuming you have the following HTML structure:
// <div id="parent">
// <p id="first">First</p>
// <span id="second">Second</span>
// <div id="third">Third</div>
// </div>
const secondElement = document.getElementById('second');
const siblingsOfSecond = getSiblings(secondElement);
// Log the siblings to the console (for demonstration):
console.log(siblingsOfSecond); // This will log an array containing the <p> and <div> elements.
// You can also iterate through the siblings and perform actions on them:
siblingsOfSecond.forEach(sibling => {
console.log(sibling.id); // Logs "first" and "third"
// Example: Change the background color of the siblings
// sibling.style.backgroundColor = 'lightgray';
});
// Handling edge cases:
// 1. Node is null:
console.log(getSiblings(null)); // Returns an empty array []
// 2. Node has no parent:
const detachedNode = document.createElement('div');
console.log(getSiblings(detachedNode)); // Returns an empty array []
Key improvements in this revised code:
- Handles edge cases: The code now explicitly handles cases where the input
node
isnull
or doesn't have a parent node, returning an empty array in these situations to prevent errors. - Clearer variable names: Using
parent
instead ofparentNode
improves readability. - More efficient iteration: Directly using
parent.children.length
is slightly more efficient than calculating the length separately. - Comprehensive example usage: The example demonstrates how to use the function, log the results, and iterate through the returned siblings to perform actions on them. It also includes the HTML structure for context and demonstrates handling the edge cases.
- Commented code: The code is well-commented, explaining the purpose of each section and how to use the function.
This improved version is more robust, easier to understand, and provides a more complete example of how to use the function in a real-world scenario.