You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何从子元素获取主父节点元素的属性值?点击子元素时能否获取父tr的data-id属性?

How to Retrieve Parent <tr>'s data-id When Clicking a <span> (No Event Binding on <tr>)

Hey, I've got you covered here! Since you already have event.stopPropagation() in place to prevent bubbling to parent elements, here's how you can grab that data-id from the parent <tr> without binding an event directly to the tr itself:

The Solution

Use the Element.closest() method to traverse up the DOM tree from the clicked <span> and find the nearest <tr> ancestor. Then you can fetch its data-id attribute using either the HTML5 dataset API or getAttribute().

Updated Code

First, here's the modified function with the logic added:

function getDataIdOfTheCurrentRow(event) {
  // Stop propagation to avoid triggering parent element events
  event.stopPropagation();
  
  // Get the clicked span element
  const clickedSpan = event.target;
  
  // Find the closest parent <tr> element
  const parentTr = clickedSpan.closest('tr');
  
  // Retrieve the data-id value (two valid approaches)
  const rowId = parentTr.dataset.id; 
  // OR: const rowId = parentTr.getAttribute('data-id');
  
  // Use the ID as needed (e.g., log it)
  console.log('Current row data-id:', rowId);
}

Your HTML stays the same, no changes needed there:

<tr data-id="1"> 
  <div> 
    <div> 
      <div id="text-wrapper"> 
        <span onclick="getDataIdOfTheCurrentRow(event)">some text</span> 
      </div> 
    </div> 
  </div> 
</tr>

Why This Works

  • event.target references the exact <span> that was clicked (since the event is directly bound to it).
  • closest('tr') efficiently climbs up the DOM tree until it finds the first <tr> element, regardless of how many nested divs are in between. This is way more robust than chaining parentNode calls (like clickedSpan.parentNode.parentNode...), which would break if your DOM structure ever changes.
  • dataset.id is a clean, modern way to access data-* attributes, while getAttribute('data-id') is a more compatible option for older browsers (though modern browsers support both well).

内容的提问来源于stack exchange,提问作者Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 22:08:14