Issue
I have the following HTML table format (just showing one row out of many) which has a button on the last cell:
<div id=main>
<div class='info'>
<p>Name: <span class='x'>ABC</span></p>
<p>Number: <span class='x'>0</span></p>
<table class='newTable'>
<tr>
<th>
Number
</th>
<th>
Value
</th>
<th>
Go
</th>
</tr>
<tr>
<td>
0
</td>
<td>
<span class='k'>11.7</span>
</td>
<td>
<button class='go'>Go</button>
</td>
</tr>
</table>
</div>
</div>
I have an eventListener (mainEntries.addEventListener('click', clickFunction)
) which triggers whenever inside <div id = main> ... </div>
I am not allowed to change the HTML. I have two questions:
- How do I check inside
function clickFunction(e)
if I clicked on the button "GO" or somewhere inside<div id = main> ... </div>
***inside clickFunction(e)
e is the MouseEvent
- If I click on the button how can I get the text inside first cell of the same row?
Solution
As already was mentioned, you can use e.target
to get clicked element. Then, you can use combination of closest()
and cells.item()
functions of the found button:
const mainEntries = document.querySelector('#main');
const clickFunction = e => {
if (e.target.tagName === 'BUTTON' && e.target.classList.contains('go')) {
const firstCellSameRow = e.target.closest('tr').cells.item(0).innerText;
console.log('GO button clicked. First cell\'s text at the same row is ', firstCellSameRow);
}
else {
console.log('Main div clicked outside of GO button');
}
}
mainEntries.addEventListener('click', clickFunction);
<div id=main>
<div class='info'>
<p>Name: <span class='x'>ABC</span></p>
<p>Number: <span class='x'>0</span></p>
<table class='newTable'>
<tr>
<th>
Number
</th>
<th>
Value
</th>
<th>
Go
</th>
</tr>
<tr>
<td>
0
</td>
<td>
<span class='k'>11.7</span>
</td>
<td>
<button class='go'>Go</button>
</td>
</tr>
<tr>
<td>
2
</td>
<td>
<span class='k'>8.5</span>
</td>
<td>
<button class='go'>Go</button>
</td>
</tr>
</table>
</div>
</div>
I added another distinct row for showing different logs.
Answered By - Andriy Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.