AI solution for JavaScript Coding Question on BFE.dev
158. Previous Left Sibling
One possible solution is to start from the target element and use the previousSibling
property to traverse the DOM tree towards the left until finding a non-empty, non-text node. Here's the code:
function previousLeftSibling(target) { let node = target.previousSibling; while (node && node.nodeType !== Node.ELEMENT_NODE) { node = node.previousSibling; } return node || null;}
This function takes a DOM element as input and returns the previous left sibling element, or null
if there isn't one. It uses a while
loop to iterate over the siblings until finding the first non-empty, non-text element node. If the loop reaches the beginning of the sibling list (i.e., node
is falsy), the function returns null
.
The time complexity of this solution is O(n), where n is the number of siblings of the target element. The worst-case scenario is when the target element is the last child of its parent, in which case we have to traverse all its siblings before finding the previous left sibling (or reaching the beginning of the list). The space complexity is O(1), as we only use a constant amount of extra memory to store the current node reference during the traversal.