I am writing a program that will generate a set of HTML tables, each with an (obviously) unique ID. Certain of the cells in each table have onClick handlers (and each also has a unique id). I want to be able to get the table id on clicking a cell to use it as a parameter in the function I'm calling onClick.
This question has been asked previously (and answered) specifically for JQuery, but I would prefer to do it in pure JavaScript. I assume it must be possible, but how?
I am writing a program that will generate a set of HTML tables, each with an (obviously) unique ID. Certain of the cells in each table have onClick handlers (and each also has a unique id). I want to be able to get the table id on clicking a cell to use it as a parameter in the function I'm calling onClick.
This question has been asked previously (and answered) specifically for JQuery, but I would prefer to do it in pure JavaScript. I assume it must be possible, but how?
Share Improve this question edited May 23, 2017 at 12:14 CommunityBot 11 silver badge asked Jul 1, 2016 at 16:42 DavidDavid 1,0501 gold badge13 silver badges23 bronze badges 14- I see this has immediately attracted two down-votes. A ment explaining why would be appreciated. – David Commented Jul 1, 2016 at 16:47
-
this.id
contains the ID of the element the event handler is bound to. It's that simple. – Niet the Dark Absol Commented Jul 1, 2016 at 16:47 - Since you're generating the table, why can't you just put the table id to the onclick handler at the same time? – JJJ Commented Jul 1, 2016 at 16:47
- 1 @NiettheDarkAbsol — Surely this.id gives me the id of the td cell, not that of the table? I use this in my event handler to send the td object to the function. – David Commented Jul 1, 2016 at 16:50
-
2
Make a generic function that accepts an element and a selector, and traverse up the
.parentElement
s untilel.matches(selector)
. – user1106925 Commented Jul 1, 2016 at 16:53
2 Answers
Reset to default 6Please try the following:
var tds = document.getElementsByTagName("td");
var getParentTableID = function() {
var el = this;
while ((el = el.parentElement) && el.nodeName.toUpperCase() !== 'TABLE');
console.log(el.id);//Table id
};
for(var i = 0; i < tds.length; i++) {
tds[i].onclick = getParentTableID;
};
<h4>Table1</h4>
<table id="tableID_1">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td id="b3">6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
<h4>Table2</h4>
<table id="tableID_2">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td id="b3">6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
Try it:
<table id="Test">
<tr>
<td onclick="test(this)">teste</td>
<td>teste</td>
</tr>
</table>
<table id="Test2">
<tr>
<td onclick="test(this)">teste</td>
<td>teste</td>
</tr>
</table>
<script>
function test(obj) {
while(obj.tagName.toUpperCase() !== "TABLE") {
obj = obj.parentNode;
}
console.log(obj.id);
}
</script>