Javier dc Javier dc - 2 years ago 146
HTML Question

Javascript access childNode

I have the following problem and I have not found a way to solve it. I'm using a dynamically generated table, which consists of 4 columns: a checkbox, text values ​​and a hidden input.

echo "<tr><td><div class='input-containerh'><input type='checkbox'></div></td>";
echo "<td>" .$s. "</td>";
echo "<td>" .$L. and some vars............ "</td>";
echo "<td><input type='hidden' value=" . some vars.... "></td>";
echo "</tr>";

As I want to format the checkbox, because in some browsers the cell makes me too big, I use a DIV to format input (checkbox) and it works good for me.

Now the problem is a javascript function that detect if the input was select and now does not work me:

function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;

for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {

Using firebug I found that the problem was:

var chkbox = row.cells[0].childNodes[0];

because it refers to "DIV" not at "input".

How i can reach the "input" element that is within "DIV" and also inside the cell?

Thanks for help.

Answer Source

Since the var chkbox = row.cells[0].childNodes[0] worked with this HTML:

<tr><td><input> type='checkbox'></td>

changing the HTML as follows:

<tr><td><div class='input-containerh'><input> type='checkbox'></div></td>

means that row.cells[0].childNodes[0] will now point to the div element. To get the input element inside div, you just access the next level of children with childNodes. So, in a nutshell, you can get access to your input with this:

var chkbox = row.cells[0].childNodes[0].childNodes[0];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download