0

I am capturing keydown event for my document. This event can be fired from anywhere in the document. The document is made up of several divs. I want to determine if the HTML element that fired keydown event is descendant of particular div. Lets say I have the documnet which looks like this:

<div class="div1">...</div>
<div class="div2">
    <div>
        <div>
            <input type="text" id="txt1"/>
        </div>
    </div>
</div>
<div class="div3">...</div>  

If txt1 fires keydown event I need to determine if it is descendant of div2. txt1 could be immediate child or grand-child or so on. Please let me know how can we do it?

user
  • 568
  • 5
  • 19

3 Answers3

1

Use .matches to see if an element matches a particular selector:

document.querySelectorAll('input')
  .forEach((input) => {
    input.addEventListener('keydown', (e) => {
      if (e.target.matches('.div2 input')) console.log('matches');
      else console.log("doesn't match");
    });
  });
<div class="div2">
  <div>
    <div>
      <input type="text" id="txt1" />
    </div>
  </div>
</div>
<input type="text" id="txt2" />
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Take a look at the Node.parentElement and ParentNode.children properties provided by Javascript. In this way, you can determine if the parent element is div1 or div2.

TheRealPetron
  • 31
  • 2
  • 6
0

If you prefer to use jquery you can do this

$('inputValue').keydown(function(){
    if($(this).closest('your class name , or div')){
    console.log('inside');
  }

});

if it returns true then it means your element is inside that particular div value otherwise its not

Syed Abdur Rehman Kazmi
  • 1,640
  • 3
  • 13
  • 30