2016-07-28 62 views
0

我怎樣才能在下面的代碼中添加一個新列, 我需要這種情況發生,如果沒有表ID或TR ID或TD ID。添加新的列到HTML表中沒有表ID

請檢查並告訴我

<p>Click the button to insert new cell(s) at the beginning of the table row.</p> 

<table> 
    <tr> 
    <td>First cell</td> 
    <td>Second cell</td> 
    <td>Third cell</td> 
    </tr> 
</table><br> 

<button onclick="myFunction()">Try it</button> 

<script> 
function myFunction() { 
    var row = ?????????????? 
    var x = row.insertCell(0); 
    x.innerHTML = "New cell"; 
} 
</script> 
+0

所以你只想得到任何表的引用沒有ID,或沒有ID任何TR,或沒有ID的TD?在那個例子中,這將是該表中的每一個元素 - 是嗎? – Whothehellisthat

回答

0

通過@ a.u.b使用var row = document.getElementsByTagName("table")[0].rows[0];是好的,但我想提使用XPath一種替代方法提供了答案。

您可以檢查元素,然後選擇表並右擊 - >複製 - >複製XPath

然後你可以用下面的代碼來獲得所需的元素:

var elementTable = document.evaluate('/html/body/table' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; 
if (elementTable != null) { 
    //do something 
} 

這裏的JsFiddle Demo

0

嘗試這個

\t \t \t \t function myFunction(){ 
 
\t \t \t \t \t var row = document.getElementsByTagName("table")[0].rows[0]; 
 
\t \t \t \t \t var x = row.insertCell(); 
 
\t \t \t \t \t x.innerHTML = "Last"; 
 
\t \t \t \t } 
 
\t \t
\t <table border="1"> 
 
\t \t \t <tr> 
 
\t \t \t \t <td>First</td> 
 
\t \t \t \t <td>Second</td> 
 
\t \t \t \t <td>Third</td> 
 
\t \t \t </tr> 
 
\t \t </table> 
 
\t \t <br /><br /> 
 
\t \t <button onclick="myFunction()">Try it</button>

相關問題