0

I have an HTML like -

<main>
<section>
  <div class="parent">
    <div class='level_1'>
      <div class='level_2'>
        <div class='level_3'>
          <span class='click_here'></span>
        </div><!--level 3-->
      </div><!--level 2-->
    </div> <!--level 1-->
  </div> <!--parent-->
<section>

<section>
  <!-- same as given above -->
<section>
<main>

See there is a span element of class click_here. So If user clicks to this span element I want to grab its grand parent element with having class parent by Javascript.
I know the basic solution like accessing e.parentElement.parentElement.parentElement.parentElement but this is not good because the clicked item might be in more deep level than given in example.
Is their any other solution by using Javascript ?

carl johnson
  • 415
  • 3
  • 10

2 Answers2

2

You could do e.target.closest('.parent') which lets you select the closest parent with whatever selector you're looking for.

lusc
  • 1,206
  • 1
  • 10
  • 19
2

You can use mouseEvent.target.closest('.parent'); to fetch the closest .parent element of the clicked element and this will work for any arbitrary nesting level. Example:

let span = document.querySelector('span');

span.addEventListener('click', function(e) {
 console.log(e.target.closest('.parent'));
});
span {
 display: block;
 width: 100px;
 height: 100px;
 background: tomato;
}
<main>
<section>
  <div class="parent">
    <div class='level_1'>
      <div class='level_2'>
        <div class='level_3'>
          <span class='click_here'></span>
        </div><!--level 3-->
      </div><!--level 2-->
    </div> <!--level 1-->
  </div> <!--parent-->
<section>

<section>
  <!-- same as given above -->
<section>
<main>
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98