I have the following table:
<table>
<tr><td><span onClick='toggleFunction();'>ABC</span></td></tr>
<tr><td><span onClick='toggleFunction();'>PQR</span></td></tr>
<tr><td><span onClick='toggleFunction();'>XYZ</span></td></tr>
<tr><td><span onClick='toggleFunction();'>LMN</span></td></tr>
</table>
The HTML is dynamically generated.
function toggleFunction() {
var innerHtml = //code to get inner html of calling element here
console.log(innerHtml);
}
I want to get the inner html of span
from which toggleFunction()
is invoked through onClick
.
For e.g. when the click is on row 1, ABC
should get printed on console. But when the click is on row 3, XYZ
should be printed.
Is this possible through Javascript or Dojo? I can not use Jquery. However, I would like to know if this is possible using Jquery or not.
Please note that the span
element is without any id.
This is not a duplicate of other question as:
1) The accepted solution uses inline javascript just to alert innerHTML. However, for me, I just want a way to gain a Handle, so that I can do far more required processing inside my function.
2) Other answers on the question are using element id, which is not my case.
You could use event.target
to target the clicked element then get the content using textContent
like :
var innerHtml = event.target.textContent;
NOTE 1: The td
should be closed before tr
so use </td></tr>
at the end instead of </tr></td>
.
NOTE 2: You have a typo in the variable passed to console.log()
, It should be innerHtml
instead of innnerHtml
.
NOTE 3: Since you've no HTML inside the columns it will be better to use textContent
instead of innerHTML
.
function toggleFunction() {
var innerHtml = event.target.textContent;
console.log(innerHtml);
}
<table>
<tr>
<td><span onClick='toggleFunction();'>ABC</span></td>
</tr>
<tr>
<td><span onClick='toggleFunction();'>PQR</span></td>
</tr>
<tr>
<td><span onClick='toggleFunction();'>XYZ</span></td>
</tr>
<tr>
<td><span onClick='toggleFunction();'>LMN</span></td>
</tr>
</table>