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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
thiloilg
  • 1,733
  • 2
  • 18
  • 23
  • Possible duplicate of [this](https://stackoverflow.com/questions/2234979/how-to-check-in-javascript-if-one-element-is-contained-within-another) – Eldar Nov 17 '19 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. – thiloilg Nov 17 '19 at 13:12

2 Answers2

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>
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
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.

Eldar
  • 9,781
  • 2
  • 10
  • 35