I am attempting to create a script to add another row in a table with specific html content. The problem is that i'd like to use the same script on each section of a rather long form. Selecting the table id without having to do so with the exact table name seems to be escaping me.
The point here is to just hit the "add" button and it will add an additional item of whatever section that button is in. But before i can have it add I need to be able to select the correct item (the table id) without actually using "getElementById".
I've scoured for an answer and being still pretty new to web javascripting, i'm guessing i'm just not understanding something or attempting the wrong method... any assistance would be greatly appreciated.
HTML
<div id="divOne">
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
</table>
<br />
<button onclick="myFunction()">Test ONE</button>
</div>
<br />
<div id="divTwo">
<table id="testTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
</table>
<br />
<button onclick="myFunction()">Test TWO</button>
</div>
jquery
function myFunction() {
var x = event.currentTarget.parentNode.getAttribute('id');
alert(x); //to test its grabbing correct div THIS ONE WORKS
var child = x.getElementsByTagName('table').getAttribute('id');
alert(child); //to test its grabbing correct THIS ONE DOESNT
}
There are two issues need to be fixed:
According to your implementation, x is the id of the parent div (string value), you can't invoke the 'getElementsByTageName('table') on it. You should get the element reference
getElementsByTagName() will return a HTMLCollection, try to access them like this: children[index]
HTML
<div id="div1">
<table id="ans"></table>
<button onClick="test(event)">test</button>
</div>
JS
function myFunction(e){
var target = e.currentTarget.parentNode;
//fetch id
console.log(target.getAttribute("id"));
//fetch table id
console.log(target.getElementsByTagName("table")[0].getAttribute("id"));
}
Here is the jsfiddle demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With