When I click, I expect to retrieve the tr element, but instead, I am receiving the td element

When I have a table and click on a tr element, the function returns a td element instead. Can someone explain why this is happening?

let func = function () {
    $("tr").on("click", (event) => {
        event.preventDefault();
        event.stopPropagation();
        console.log(event.isPropagationStopped()); // true

        let targetEl = $(event.target);
        console.log(targetEl); // Object [ td ]
    });
};

func();

I would like the "onclick" to return the tr element instead of the td, but I'm not sure what's causing this issue. Any help would be appreciated.

Answer №1

Exploring currentTarget and closest methods in jQuery

$("tr").on("click", (event) => {
  event.preventDefault();
  event.stopPropagation();
  console.log('target:', event.target.tagName)
  console.log('target closest:', event.target.closest('tr').tagName)
  console.log('currentTarget:', event.currentTarget.tagName)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>1</td>
  </tr>
  <tr>
    <td>2</td>
  </tr>
</table>

Answer №2

The reason why the click event didn't reach the parent element is because you interrupted the event propagation. JavaScript typically follows a bubbling method for event propagation. If you want more detailed information, check out this insightful article.

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

Modify the length of an array using a number input field

Currently, I am working with an array that contains objects and I want to dynamically change the number of objects in this array based on user input from a number type input box. Whenever the number in the input box is increased, I need to increase the len ...

Discover the steps to traverse through directories and their numerous subdirectories (including a whopping 15000 subdirectories) with the help of the directory-tree

We are currently utilizing the directory-tree npm package to access and read through all directories and subdirectories, noting that there are as many as 15000 nested subdirectories. Code snippet in use: const dirTree = require("directory-tree"); const ...

Attempting to incorporate a factory within a restricted function

Just starting out with AngularJS and I have a question. Can I use a factory code (logger) inside a private function like the example below? I'm still working on understanding angular concepts. Thanks for your help: (function () { 'use strict ...

Is there a way to retrieve a specific item from an array using a different method than just its position with jsRender?

I am currently working on rendering JSON data using jsRender. Take a look at the sample JSON data below: "PageContentList": [ { "ContentId": 51, "Title": "60 seconds with Rick", "ContentMediaTypeList": [ { ...

Tips for displaying the data on top of individual column bars: Hightcharts, Vue-chartkick, and Cube Js

Looking for assistance with adding value labels to the top of each column bar in a Vue chart using chartkick and highcharts. https://i.sstatic.net/c4Bwc.jpg Check out the image above to see my current output. <template> <column-chart lable= ...

"Utilizing Vue Mixins on a global scale, but restricting their usage to local components

Is there a way to use a mixin in multiple components without having to constantly import and declare it? I've tried connecting the mixin object to a global variable using vue.prototype, but mixins are added to components before globals are accessible. ...

When modifying the variable with an index in React JS, all objects with the same key but different indexes are also altered

I attempted to modify the array of objects, specifically creating a task list that includes user name, task description, and other details. However, when I update the task at the first index, all the objects with different array indexes also get modified. ...

Asking for information regarding RESTful API

Could you please assist me in identifying the most suitable technologies for integrating a RESTful API into an HTML and CSS website? The primary objective is to enable the website owner to easily log in and add news entries about their business. Addition ...

Step-by-Step Guide: Crafting a Non-Ajax Popup Chat Application

Recently, I created a unique dating website with a one-to-one chat feature similar to Facebook. However, I implemented this using the ajax technique and the setInterval function in JavaScript for regular updates. Upon reflection, I believe that this appr ...

Tips for automatically expanding all nodes with children when the page loads in the Wix Angular tree control

Is there a way to automatically expand all nodes with children when the page loads in an Angular tree control? The tree control is full of useful features, but this specific functionality seems to be missing. It does have a property for expanded nodes. Do ...

Test fails in Jest - component creation test result is undefined

I am currently working on writing a Jest test to verify the creation of a component in Angular. However, when I execute the test, it returns undefined with the following message: OrderDetailsDeliveryTabComponent › should create expect(received).toBeTru ...

What is the method to generate an array of values using a single attribute in GeoJSON data?

Note: After reviewing some possible solutions mentioned in this thread, I found that .map is the perfect fit for what I need, which was not covered in the original post. Thomas's response below addresses my specific requirement. In JavaScript, how ca ...

Tips for extracting Stripe response post payment using a client-side-only integration

My current component handles sending a payment order to my stripe account on the client-side. Everything seems to be working fine, but I'm struggling to find a way to retrieve the response or token from stripe containing the order details, which I nee ...

Issue with Passing 'key' Prop to React Component in a Mapped Iteration

https://i.sstatic.net/qeFKT.pngI'm struggling with adding a key prop to a React component in a mapped array within a Next.js project. The issue lies in a Slider component and an array of Image components being mapped. Even though I have provided a uni ...

The Viadeo Social Toolbox seems to be encountering technical difficulties at the moment

I attempted to utilize a Viadeo Social Toolbox, specifically the Viadeo Share Button, but it seems to be malfunctioning in certain browsers? I came across some outdated viadeo share URLs like this: http://www.viadeo.com/shareit/share/?url=${url}&title ...

Updating the model of a Vuejs single file component (.vue) within the <script> tag

Discovering the world of vuejs, I set out to create a basic single file component for testing purposes. This component's main task is to showcase a boolean and a button that toggles the boolean value. It also listens for a "customEvent" which trigger ...

Create a unique filter in an ng-repeat directive that allows users to personalize the data displayed

Is there a way to create a custom filter that hides the inventory column for Color Pencil Special on October 2nd, 2017 in the view? The inventory for Color Pencil Special is dependent on the inventory of regular Color Pencils, which are stored somewhere e ...

Merging scripts to minimize HTTP requests - The Takeover of the Body Swappers

For my website design, I've implemented the Invasion Of The Body Switchers script from brothercake.com. This script involves loading three separate js files in the header. I'm looking to optimize my site by reducing the number of HTTP requests a ...

Displaying HTML with AngularJS dynamic data-binding

Here is a sample view: <div ng-show=""> <div style='background-color: #13a4d6; border-color: #0F82A8'> {{headerdescription}} <div style='float: right'>{{price}} $</div> </div> <div style=&apos ...

Clicking on "Ng-Click" will add a fresh row to the table using Angular

Is there a way to insert a new row into a table using ng-click? I currently have the following setup with the data stored in an array. Here is how my array looks. $scope.workflows = [{ Id: 1, Name: "Workflow Page 1", ...