1

What is the best way to find out if a given element (targetElement) is inside of an element with a specific type like for example an anchor in pure JavaScript?

(html)

<a href="/"> <div class="AnElementInBetween"> <div class="anotherElementInBetween"> <div class="targetElement" onclick="handleClick()"> Am I inside an anchor element? </div> </div> </div> </a> 

(js)

function handleClick(event){ // event.target Am I inside an anchor? } 

Since some people have seen a duplicate in this question, just to make this clear. The questions looks for a solution to check if the element is surrounded by a specific element type not a specific element itself.

2
  • Possible duplicate of this Commented Nov 17, 2019 at 12:03
  • @Eldar The question asks for an element type, not an element, where you simply could use .contains(). Also your comment seems to be a duplicate since you postet it twice. Commented Nov 17, 2019 at 13:12

2 Answers 2

1

You can do it recursively. The function breaks if it reaches body and not found yet.

function handleClick(event){ event.preventDefault(); event.stopImmediatePropagation(); // event.target Am I inside an anchor? const has = hasParentOfType(event.target, 'A'); console.log(has); } function hasParentOfType(node, type) { if (type !== 'BODY' && node.nodeName === 'BODY') return false; if (type === node.nodeName) return true; return hasParentOfType(node.parentNode, type); }
<a href="/"> <div class="AnElementInBetween"> <div class="anotherElementInBetween"> <div class="targetElement" onclick="handleClick(event)"> Am I inside an anchor element? </div> </div> </div> </a>

Sign up to request clarification or add additional context in comments.

Comments

0

function handleClick(e) { var meInside = isDescendant("A", e.target); if (meInside) { console.log("YES"); } } function isDescendant(parent, child) { var node = child.parentNode; while (node != null) { if (node.nodeName === parent) { return true; } node = node.parentNode; } return false; }
<a href="#"> <div class="AnElementInBetween"> <div class="anotherElementInBetween"> <div class="targetElement" onclick="handleClick(event)"> Am I inside an anchor element? </div> </div> </div> </a>

I still think it is duplicate. I copied the answer from the link i posted on comment. Since you require element type i changed it to check the node's nodeName property and that's it. Please notice that node names is all upper case.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.