It’s hard to diagnose this problem without the complete reduced test case. Your codepen example doesn’t really demonstrate the problem as there’s only one table being created. Without seeing the code you’re writing for the second table it’s difficult for us to help you debug this problem.
I see you’re using string concatenation to build up your table before inserting it into the page. Is this a requirement of the assignment? If not, you should consider using createElement, insertBefore, and appendChild along with innerHTML and innerText to build up your table structure instead.
Then it will be easier to manipulate the dynamic nodes you’re inserting into the page and that could contribute to less “confusing” things happening.