2017-08-05 114 views
1

我想更改此表格中“开始日期”列的innerText。如何更改表格上某一列的内容?

下面的代码:

<tr id="currentRow"> 
    <th>Name</th> 
    <th>Position</th> 
    <th>Office</th> 
    <th>Age</th> 
    <th>Start date</th> 
    <th>Salary</th>   
</tr> 

我想下面这段代码,但没有奏效。

document.getElementById("currentRow").td[4] = "this is a text"; 

我该如何实现它?

回答

0

您需要添加.innerHTML如果你想使用querySelectorAll更改所选元素的内容,如:

document.querySelectorAll('#currentRow th')[4].innerHTML = "this is a text"; 

注:请确保您的表包含至少一个td

希望这会有所帮助。

document.querySelectorAll('#currentRow th')[4].innerHTML = "this is a text";
<table> 
 
    <tr id="currentRow"> 
 
    <th>Name</th> 
 
    <th>Position</th> 
 
    <th>Office</th> 
 
    <th>Age</th> 
 
    <th>Start date</th> 
 
    <th>Salary</th> 
 

 
    </tr> 
 
</table>

+0

但getElementById不适合我,querySelectorAll正在工作。 – djmayank

+0

可能导致没有.td属性? :/ –

+0

是的,如果没有'td'元素,它不会工作。 –

0

<table> 
 
<tr id="currentRow"> 
 
    <th>Name</th> 
 
    <th>Position</th> 
 
    <th>Office</th> 
 
    <th>Age</th> 
 
    <th>Start date</th> 
 
    <th>Salary</th>   
 
</tr> 
 
</table> 
 
<script> 
 
document.getElementById("currentRow").children[4].innerHTML = "this is a text"; 
 
</script>

世界上没有TD在元件而是儿童阵列。

+0

谢谢!这工作。 – kreatusJohn

+0

@ user3080440很高兴提供帮助;)当这个问题得到解答时,现在你的工作是打开这两个答案中的一个的绿色对号(zakaria是第一个,只是说);) –