Skip to content
Advertisement

How to capture the most exterior element when click event occurs

I need to get the most element when clicking in a div… Such as this…

 <div id="show_trash_id" class="switch switch-xs">
   <input type="checkbox"/>
   <span class="slider round">
     <span class="text-on">ON</span>
     <span class="text-off">OFF</span>
   </span>
 </div>

I think that this is related to some sort of bubbling or capturing effect., however I cannot handle that… I have already tried to do event.stopPropagation() or using useCature both unsuccessfully.

function capture (event) {
   event.stopPropagation();
   console.log(event.target);
}
document.querySelector('#show_trash_id').addEventListener('click', capture, true) 

In short what I want is to get the following bellow displayed in the console:

     <div id="show_trash_id" class="switch switch-xs">
       <input type="checkbox"/>
       <span class="slider round">
         <span class="text-on">ON</span>
         <span class="text-off">OFF</span>
       </span>
     </div>

Advertisement

Answer

I have had this problem before. My solution has always been to use an anonymous function and use the this keyword instead of event.target, as it refers to the element the event listener was added to.

Note however that the anonymous function cannot be an arrow function, as this in the context of an arrow function is the window.

document.querySelector('#show_trash_id').addEventListener('click', function(e) {
  console.log(this);
});
 <div id="show_trash_id" class="switch switch-xs">
   <input type="checkbox"/>
   <span class="slider round">
     <span class="text-on">ON</span>
     <span class="text-off">OFF</span>
   </span>
 </div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement