Ways to grab the outermost element when a click event happens

When I click on a div, I want to retrieve the innermost element like so:

<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 believe this involves bubbling or capturing effects, but I am having trouble with it. I have tried using event.stopPropagation() and useCapture, but without success.

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

In summary, I am looking to display the following in the console log:

<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>

Answer №1

Dealing with this issue in the past, I've always found success by utilizing an anonymous function and leveraging the this keyword instead of relying on event.target. This allows for reference to the element where the event listener was attached.

It's worth noting that the anonymous function cannot be an arrow function since using this within an arrow function context will refer to the window object.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Removing duplicates from a multidimensional array by comparing the first element in each subarray using Javascript

I need to obtain unique values from a multidimensional array. The uniqueness should be based on the first element of each item. let arr = [['item 1', 'item 2'],['item 1', 'item 5'],['item 3', 'item 4& ...

In Nodejs, the function 'require' fails to load a module when using specific filenames

Hello everyone, I am a long-time user but this is my first time asking a question. So, I have a file named file.js where I am trying to require another file called user.service.js at the beginning of the file: var userService = require('./user.servi ...

I have to ensure that a plugin is only loaded once its dependency has been loaded with RequireJS

Currently, I am utilizing the jquery.validationEngine.js plugin and facing an issue. It seems that jqueryValidateEnglish is unable to function properly unless jqueryValidateEngine is loaded beforehand. In my code for jquery.wrapped.validationEnglish2.js, ...

Ways to pass properties while using render in reachrouterdomv6?

Currently, I am enrolled in a Udemy course, but the information provided is based on v5. I am struggling to understand the equivalent of "render" and how to pass props with it. Additionally, there seems to be an issue with the code - if the element is un ...

Leverage React components for efficient code reuse and export modules for

I have Project X, which was built using the command "yarn build" and it generated a main.js file. I am trying to use this main.js file as a dependency for another React project Y. Unfortunately, following the steps from React components and module exports ...

Can a client receive a response from server actions in Next.js 13?

I'm currently developing a Next.js application and I've created an action in app/actions/create-foo-action.js. In this server action, I am attempting to send a response back to the client. import { connectDB } from "@utils/database" imp ...

When trying to invoke an Angular function from a JavaScript function, it is returning as undefined

When attempting to invoke an Angular function from a JavaScript function, I am encountering an issue where it is displaying as undefined. Below is an example demonstration I have created: import { Component, NgZone, OnInit } from '@angular/core&apo ...

Updating the state of a disabled field in a React component

I have been trying to display a default value and disable the field. The values are successfully displayed but the state is not getting updated. Can someone please guide me on how to update the state of a disabled field? I have put in a lot of effort but h ...

Combining input streams using node.js and ffmpeg

Currently, I'm in the process of developing a basic and straightforward Video-Web-Chat platform. My approach involves utilizing the getUserMedia API call on the client side to capture webcam data and transmit it as data-blob to my server. My plan is ...

The function is producing 'undefined' output despite having the correct result within its body

My HTML file contains the following content: <div class="ui-btn-text"> <a id="12323" class="listviewLines ui-link-inherit" href="" /></div> <div class="ui-btn-text"> <a id="23534" class="listviewLines ui-link-inherit" href="" /& ...

What is the best way to create a list from a matrix using JavaScript?

I have an array structured as follows: const input_array= [ ["red", "green"], ["small", "medium"], ["x", "y", "z"] //... can have any number of rows added dynamically ...

Modifying the CSS class of an element does not produce the desired effect after altering its styles using JavaScript

html: <input id="myinput" class="cinput" type="image" src="http://www.foodwater.org.au/images/triple-spiral-3-small-button.jpg"/> <br><br><br><br> <button id="s">set to visible class</button> <button id="h"> ...

Clearing existing HTML content in the TR body

I've been struggling with a Jquery/Ajax call that updates cart details. Currently, I can't seem to clear the existing HTML content in the cart-body (tablebody) even though the ajax request adds all the items to the cart successfully. The code sni ...

What is the best way to send information to the nested component's inner scope?

I am facing an issue with rendering a list of request/response pairs in my controller using components(directives). It appears that only string attributes are being passed to the component's scope, while objects are being ignored. You can view the f ...

Is there a way to connect cell values to correspond in Google Sheets?

I have a spreadsheet on Google Sheets containing financial data from companies' statements. This includes both quarterly and annual information, with a dropdown cell at the top allowing me to choose between "Annual" and "Quarterly" data. However, scro ...

What are the best practices for establishing a secure SignalR client connection?

While tackling this issue may not be solely related to SignalR, it's more about approaching it in the most efficient way. In C#, creating a singleton of a shared object is achievable by making it static and utilizing a lock to prevent multiple threads ...

Using Three.js to load blender JSON files

Hey there! I'm currently facing some challenges when it comes to importing models from Blender into three.js. Currently, I am using the latest version of three.js (R71). I have successfully installed the three.js exporter in Blender and it works fine ...

Tips for resolving the error message "What to do when reportWebVitals can't be located

Having some trouble with importing reportWebVitals for my React 18 application that is based on WebPack 5. Below is a snippet of my index.tsx file: import React from 'react'; import ReactDOM from 'react-dom/client'; import './style ...

Using an if/else statement to detect if the iFrame is devoid of content

I have a customized youtube video section on my website template that can display either an embedded video or an image based on client preference. Currently, I am trying to implement code that will detect if the youtube video source is empty and then displ ...

Looking to include a data-* attribute within a div element for the utilization of a third-party JavaScript library like React or Next.js?

let speed = '{ "speed": 0.2 }'; <div className="section jarallax h-100vh" data-jarallax={speed} style={{backgroundImage: "url('/images/header-bg.jpg')"}} id="home"> </div> <Script src="./js/parallax.js" strate ...