is it possible to get the attribute 'data-id' when clicking on a child element? In the scenario below, the getDataIdOfTheCurrentRow()
method only firs when clicking on the span, not the whole record. I need to retrieve the attr value of the the parent tr
. I know I can set a method that fires when clicking on the 'tr' so I can easily access its attributes. but this is not what I am asking for.
<tr data-id="1">
<div>
<div>
<div id="text-wrapper">
<span onclick="getDataIdOfTheCurrentRow(event)">some text</span>
</div>
</div>
</div>
</tr>
function getDataIdOfTheCurrentRow(event) {
// stopPropagation is used to only fires the method when clicking on the child element, not other methods on the parent elements
event.stopPropagation();
}
CodePudding user response:
You could use closest(selector)
:
function getDataIdOfTheCurrentRow(event) {
event.stopPropagation();
const row = event.target.closest('tr');
if(row.hasAttribute('data-id')){
const dataID = row.getAttribute('data-id');
// now do your thing
}
}
CodePudding user response:
The only valid parent tag of a
<tr>
is a<table>
Wrap everything in a
<table>
The only children tag a
<tr>
can have is<td>
and<th>
Add a
<td>
directly within<tr>
remove those extra<div>
they will only clutter your layoutDo not use
id
so liberally, you'll understand when you've written your hundredth page and have a hard time overriding styles, adding JavaScript that references DOM objects, etc.Remove all
id
s and usedocument.querySelector()
to reference elements by.class
,[name]
,tagName
, etc.Don't use inline event handlers❋
<div class='target' onclick="lame(this)">DON'T DO THIS</div>
Use onevent properties or
document.querySelector('.target').onclick = eventHandler;
event listeners
document.querySelector('.target').addEventListener('click', eventHandler)
❋See below for links to articles about events
Details are commented in example
// Bind click event to an ancestor tag
document.querySelector('table').onclick = getRow;
// Event handlers only passes the Event object
function getRow(event) {
// Reference the tag that the user clicked
const clicked = event.target;
// If the clicked tag is a <button>...
if (clicked.matches('button')) {
/*
Find the closest parent <tr> get it's data-id value and convert it
into a real number
*/
console.log(parseInt(clicked.closest('tr').dataset.id));
}
}
.as-console-row::after {
width: 0;
font-size: 0;
}
.as-console-row-code {
width: 100%;
word-break: break-word;
}
.as-console-wrapper {
min-height: 100% !important;
max-width: 50%;
margin-left: 50%;
}
<table>
<tr data-id="1">
<td>
<menu>
<button type='button'>Get row number</button>
</menu>
</td>
</tr>
<tr data-id='2'>
<td>
<menu>
<button type='button'>Get row number</button>
</menu>
</td>
</tr>
<tr data-id='3'>
<td>
<menu>
<button type='button'>Get row number</button>
</menu>
</td>
</tr>
<tr data-id='4'>
<td>
<menu>
<button type='button'>Get row number</button>
</menu>
</td>
</tr>
</table>