DOM Challenge - #1

I'm planning to write around 30 posts covering various questions related to DOM traversal, manipulation, and optimization. Today's question is related to DOM traversal Question: Find the common ancestor of two given DOM elements. In this question we have DOM tree and we need to find common ancestor of given nodes. The first approach I can think of is collect all parent nodes of both elements and find the first common node. We can get parentNodes using this method const parentList = (element)=>{ let el = element; const list = []; while(true){ list.push(el); if(!el.parentNode) break; el = el.parentNode; } return list; } Now we can use this list to find LCA - const findLCA = (el1, el2)=>{ const parentList1 = parentList(el1); const parentList2 = parentList(el2); for(let i=0; i

Feb 17, 2025 - 18:53
 0
DOM Challenge - #1

I'm planning to write around 30 posts covering various questions related to DOM traversal, manipulation, and optimization.

Today's question is related to DOM traversal

Question:
Find the common ancestor of two given DOM elements.

In this question we have DOM tree and we need to find common ancestor of given nodes. The first approach I can think of is collect all parent nodes of both elements and find the first common node.

We can get parentNodes using this method

const parentList = (element)=>{
    let el = element;
   const list = [];
    while(true){
        list.push(el);

        if(!el.parentNode) break;
        el = el.parentNode;
    }

    return list;
}

Now we can use this list to find LCA -


const findLCA = (el1, el2)=>{
    const parentList1 = parentList(el1);
    const parentList2 = parentList(el2);

    for(let i=0; i

This solution works, but it has a time complexity of O(n²) due to the includes() check inside the loop.

We can improve this by using Set to store parent list, so that we can use parentList2.has(parentList1[i]), this is of O(1) complexity so time complexity for our code will be O(n).