You need to add a click event listener to the <a>
elements, and then you can access the inner HTML of the element that triggered the event. Since you are retrieving a collection of HTML elements, you should iterate through it.
One way to iterate through a collection is to simply convert it to an array using Array.from()
and then chain .forEach()
to it:
const list = document.getElementsByTagName("a");
Array.from(list).forEach(el => {
el.addEventListener('click', e => {
e.preventDefault();
console.log(e.target.innerText);
});
});
Array.from(document.getElementsByTagName('a')).forEach(el => {
el.addEventListener('click', e => {
e.preventDefault();
console.log(e.target.innerText);
});
});
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td><a href="#">Jill</a></td>
<td><a href="#">Sam</a></td>
<td><a href="#">10</a></td>
</tr>
<tr>
<td><a href="#">Eve</a></td>
<td><a href="#">Jeffreson</a></td>
<td><a href="#">55</a></td>
</tr>
</table>
However I tend to recommend using document.querySelectorAll
because you can pass CSS selectors as strings. Here is an example using document.querySelectorAll()
:
document.querySelectorAll('a').forEach(el => {
el.addEventListener('click', e => {
e.preventDefault();
console.log(e.target.innerText);
});
});
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td><a href="#">Jill</a></td>
<td><a href="#">Sam</a></td>
<td><a href="#">10</a></td>
</tr>
<tr>
<td><a href="#">Eve</a></td>
<td><a href="#">Jeffreson</a></td>
<td><a href="#">55</a></td>
</tr>
</table>