简体   繁体   中英

Javascript, how can I access a specific child of a row?

Using Javascript, how can I access a specific child of a row? Javascript (not jQuery please).

eg: second <TD> of <TR> 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>
var index = 1; // second element
var child = document.getElementById('id33322010100167').childNodes[index]

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
    }
}

最可靠的是cells集合,与非 IE 浏览器中的childNodes不同,它会忽略单元格之间的空白文本节点:

var td = document.getElementById("id33322010100167").cells[1];

I found this solution in combining the two most rated one:

Instead of using childNodes you could get Elements of typ td below this row with:

var array_td = document.getElementById('id33322010100167').getElementsByTagName("td");

To get the content of the first td you could use:

array_td[1]

The main benefit of this is, that you do not have all the whitespace you dont want to handle inside the array and you dont have to change the index if some new childs (not tds) be added.

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.

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();
<table id="studTable" class="table table-bordered">
     <thead>
        <tr>
           <td>Click</td>
        </tr>
     </thead>
     <tbody>
           <tr><td><a href="#" onclick="ClickRow(this)">Click</a></td></tr>
     </tbody>
</table>

for above table you can use something link this. you can read your selected row by clicking row/cell inside row and read cell values and/or remove row from table

function ClickRow(r) {
        console.log(r.parentNode.parentNode.cells[0].innerHTML); //Read First Cell in Row
        var i = r.parentNode.parentNode.rowIndex;
        document.getElementById("studTable").deleteRow(i); //Remove Row
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM