Pazira
Pazira

Reputation: 51

Why does the js event in this code not bubble up?

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>
    
           
    

Upvotes: 0

Views: 31

Answers (1)

Barmar
Barmar

Reputation: 780974

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>
    
           
    

Upvotes: 2

Related Questions