0

I want to be able to click on div "three" and it should bubble up to the other two?

const divs = document.querySelectorAll('div');
divs.forEach(div => div.addEventListener('click', function (e) {
  console.log(e.target.className);
}));
<div class="one">
  <div class="two">
    <div class="three">
        Hello World
    </div>
  </div>
</div>
    
           
    
tkausl
  • 13,686
  • 2
  • 33
  • 50
Pazira
  • 51
  • 4

1 Answers1

2

It does bubble up, you should get 3 log messages.

It logs three each time because e.target is the original element that the event is bubbling from. To get the current element in the propagation, use e.currentTarget. This code logs three, two, one.

See What is the exact difference between currentTarget property and target property in javascript

const divs = document.querySelectorAll('div');
divs.forEach(div => div.addEventListener('click', function (e) {
  console.log(e.currentTarget.className);
}));
<div class="one">
  <div class="two">
    <div class="three">
        Hello World
    </div>
  </div>
</div>
    
           
    
Barmar
  • 741,623
  • 53
  • 500
  • 612