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.targetreferences 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 chainingparentNodecalls (likeclickedSpan.parentNode.parentNode...), which would break if your DOM structure ever changes.dataset.idis a clean, modern way to accessdata-*attributes, whilegetAttribute('data-id')is a more compatible option for older browsers (though modern browsers support both well).
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

