views:

64

answers:

5

using javascript, how can I access a specific child of a row? javascript (not jquery please) eg: second of where ID=id33322010100167

<table>
<tr id="id33322010100167">
<td>20101001</td>
<td>918</td>
<td>919</td>
<td>67</td>
<td>CAR PROBLEM</td>
</tr>
<tr id="id33322010100169">
<td>20102001</td>
<td>913</td>
<td>914</td>
<td>62</td>
<td>LUNCHTIME</td>
</tr>
<table>
A: 

Using the DOM you can get the table and then iterate over the child elements while keeping count.

Of course element ids are supposed to be unique so that document.getElementById('id') works.

Dan Iveson
A: 

Use jQuery:

first = $('#id33322010100167 td:first'); // gives you the first td of the tr with id id33322010100167 
last = $('#id33322010100167 td:last'); // gives you the last td of the tr with id id33322010100167 

you may use next() to iterate through the elements

first.next();
Thariama
A: 
var index = 1; // second element
var child = document.getElementById('id33322010100167').childNodes[index]
RaYell
Have you tried this? This returns the first `<td>`, not the second, because the first child node of the `<tr>` is a text node containing whitespace.
Tim Down
Then just change the index to 2. The method's still good.
RaYell
@RaYell: No, it isn't. `document.getElementById('id33322010100167').childNodes[2]` will give another whitespace node. Also, what if the OP then removed all the line breaks in his source code? That preserves the order of `<td>` elements while completely changing the `childNodes` collection.
Tim Down
@RaYell: It also gives different results in IE from other browsers, since IE doesn't consider the whitespace nodes in `childNodes` whereas other browsers do.
Tim Down
+1  A: 

Most reliable is the cells collection, which unlike childNodes in non-IE browsers will ignore whitespace text nodes between cells:

var td = document.getElementById("id33322010100167").cells[1];
Tim Down
+1  A: 

Maybe you can try this:

var tRow = document.getElementById("tableName").getElementsByTagName("tr");

for(var i = 0; i < tRow.length; i++){
    if(tRow[i].id == "name of your id"){
        //do something
    }
}
Shaoz
`document.all` is not a good thing to be using these days.
Tim Down
I've taken it off
Shaoz
The other issue is that there are no ids in the `<td>` elements in the example and the OP may not want to have to add them.
Tim Down