1

In my window event, if the pointer clicks on the parent or its child/descendant, it should do something. The problem is the event can't access the parent's child and grand child. The condition is stored in the targetIsInsideParent variable.

HTML

<div class="parent">
  Parent
  <div class="child">
    Child
    <div class="grandchild">
      GrandChild
    </div>
  </div>
</div>

JS

const parent = document.querySelector('.parent');

window.addEventListener('click', e => {
  const targetIsParent = e.target === parent;
  const targetIsInsideParent = e.target === parent.children; // !!!!

  if(targetIsParent || targetIsInsideParent) {
    console.log('Good');
  }
})
jstarnate
  • 319
  • 3
  • 15
  • You have to use the `parent` chain of the target, iterating to see if one of the links is the parent element. – Pointy Nov 05 '18 at 15:30
  • @Pointy Use an Iterator? – jstarnate Nov 05 '18 at 15:33
  • Well if an element is a descendant of the parent, then either it's `.parent` references the parent, or the `.parent` of the parent, etc. – Pointy Nov 05 '18 at 15:41
  • You could also just check to see if the target matches `.parent *` via the `.matches()` API. – Pointy Nov 05 '18 at 15:43
  • You're asking if the target is the same as the child of the parent, which it's not. it's the grand child. `parent.childElementCount` is 1 – colecmc Nov 05 '18 at 15:44
  • Possible duplicate of [How to check in Javascript if one element is contained within another](https://stackoverflow.com/questions/2234979/how-to-check-in-javascript-if-one-element-is-contained-within-another) – Djurdjen Nov 05 '18 at 15:56

1 Answers1

1

Try to use parent.contains(e.target) or parent.compareDocumentPosition(e.target) === 20

const parent = document.querySelector('.parent');

window.addEventListener('click', e => {
  const targetIsParent = e.target === parent;
  const targetIsInsideParent = parent.contains(e.target);
  // const targetIsInsideParent = parent.compareDocumentPosition(e.target) === 20; // alternative, but also works good
  if(targetIsParent || targetIsInsideParent) {
    console.log('Good');
  }
})
<div class="parent">
  Parent
  <div class="child">
    Child
    <div class="grandchild">
      GrandChild
    </div>
  </div>
</div>
<div>Other</div>
qiAlex
  • 4,290
  • 2
  • 19
  • 35
  • Thanks, it's very helpful. But which should I prefer between `.contains()` and `.compareDocumentPosition()` when it comes to performance and browser support? – jstarnate Nov 05 '18 at 16:46
  • 1
    I would suggest `.contains()` because of it is little bit better supported, shorter, and I guess, that it should work faster, because it checks only `node` inner content, while `compareDocumentPosition` checks not only childs and subchilds, but also parent siblings and `node`'s parents – qiAlex Nov 05 '18 at 16:53