[英]How to access second cell of each row in a html table using javascript?
[英]JavaScript: How to access the second table inside a div using the node of the first table
我有這樣的代碼-
<div id="doc">
<div id="main">
<table id="vtier#1">
<tr>
<td><button> onclick="delVtier(this);return false;" </button></td>
<td>1.Vtier Name:
<select id="vtier" name="vtierN" onchange="populateTable(this,VtierAccountForm); return false;">
<option>ANY</option>
</select></td>
</tr>
</table>
<table id="subAccTable">
<tr>
<td>
<h2>Sub Accounts</h2>
</td>
</tr>
<tr>
<th>action</th>
<thaccount/></th>
<th>homeDir</th>
<th>primaryGroup</th>
</tr>
</table>
<script>
function populateTable(src,form) {
var div = src.parentNode.parentNode.parentNode.parentNode;
alert(div.childNodes[2].innerHTML);
}
</script>
現在在populateTable函數內部,我具有來自第一個表的select標記的節點。 使用該節點,如何到達div中第二個表的節點。 我已經嘗試過使用childNodes [2],但是它不起作用。 但是,上面的警報中的childNodes [1]可以正確打印第一個表的innerHTML。 請幫忙 !
為什么不通過document.getElementById("subAccTable")
直接訪問它?
假設變量“表”指向第一個表
var elem = table;
while(elem = elem.nextSibling){
if (elem.tagName.toLowerCase() == 'table'){
var nextTable = elem;
break;
}
}
nextTable將包含另一個表
src.parentNode.parentNode.parentNode.parentNode
實際上正在解析到您的第一個表。 (這是因為src.parentNode.parentNode.parentNode
返回tbody
元素。)您需要遍歷更高一級:
var div = src.parentNode.parentNode.parentNode.parentNode.parentNode;
盡管,正如其他人所說的那樣,通過表ID引用該表會更加干凈。
childNodes
[MDN]返回所有DOM節點的列表,還返回文本(換行符等)。 您可以使用children
[MDN]僅丟失元素節點。
而且parentNode
鏈看起來也不好。 由於您的表具有ID,因此為什么不這樣做:
var targetTable = document.getElementById('subAccTable');
或者,如果表沒有ID,則可以使用getElementsByTagName
:
var targetTable = document.getElementById('main').getElementsByTagName('table')[1];
元素索引基於零,因此div.childNodes[2]
將導致null或未定義(我不記得是哪個)。 或者您也可以像其他人建議的那樣使用document.getElementById('subAccTable')
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.