Let's assume that you have the following HTML skeleton:
html<div id = 'Z'> <div id = 'Y'> <div id = 'X'> <button onclick = "getParentId(event)"></button> </div> </div> </div>
If you want to get the top level id:
javascriptfunction getParentId(e){ let top = e.currentTarget.parentNode.parentNode.parentNode return top.id }
Is there a way to optimize (...).parentNode.parentNode.parentNode
?
javascriptfunction getParentId(e){ let top = e.currentTarget 'n'.repeat(3).split('').forEach(n => top = top.parentNode) return top.id }
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.