admin管理员组

文章数量:1291320

I have DIV and inside div it has table. I want to change the one of the column value of table using java script. I can do it by getting the element id of column, but there is no any id assigned to any table's column. Below is the example.

<div id="usersec">
<TABLE style="TEXT-ALIGN: center; WIDTH: 279px; HEIGHT: 70px">
<TBODY>
<TR>
<TD style="FONT-FAMILY: Verdana" vAlign=center align=middle>Talk to me </TD></TR></TBODY></TABLE>
</div>

Is it possible to change the "Talk to me" text using javascript?

I have DIV and inside div it has table. I want to change the one of the column value of table using java script. I can do it by getting the element id of column, but there is no any id assigned to any table's column. Below is the example.

<div id="usersec">
<TABLE style="TEXT-ALIGN: center; WIDTH: 279px; HEIGHT: 70px">
<TBODY>
<TR>
<TD style="FONT-FAMILY: Verdana" vAlign=center align=middle>Talk to me </TD></TR></TBODY></TABLE>
</div>

Is it possible to change the "Talk to me" text using javascript?

Share Improve this question edited Mar 28, 2013 at 15:06 dsgriffin 68.6k17 gold badges140 silver badges138 bronze badges asked Mar 28, 2013 at 14:43 user1591156user1591156 2,0056 gold badges23 silver badges40 bronze badges 2
  • Do you only ever have the one <td> in the table? Or are you asking us how to find a specific <td> without an id attribute, eg based on its content? – Sepster Commented Mar 28, 2013 at 14:53
  • Are you happy to use a lib, such as jQuery? – Sepster Commented Mar 28, 2013 at 14:55
Add a ment  | 

3 Answers 3

Reset to default 3

If your userbase is IE8+, you can safely use querySelector:

var container = document.getElementById('usersec');
var td = container.querySelector('tr:first-child > td');
if(td){
  td.innerHTML = "New Text!";
}

Here's a JSFIDDLE: http://jsfiddle/rgthree/YkhwE/

querySelector (or querySelectorAll) allow you to target elements in the DOM via CSS syntax, which is very useful. It's very well supported, in every current and previous browser. (via Can I Use)

Yes, you need to get the element and then set a new value to element.innerHTML. It's easiest if you give an id to the element that you want to change but you don't need to

jsFiddle

<script type="text/javascript">
    var usersec = document.getElementById('usersec');
    var td = usersec.getElementsByTagName('td')[0];
    td.innerHTML = 'New value';
</script>

You can assign an id to the TD, and use that;

<div id="usersec">
<TABLE style="TEXT-ALIGN: center; WIDTH: 279px; HEIGHT: 70px">
<TBODY>
<TR>
<TD style="FONT-FAMILY: Verdana" vAlign=center align=middle id="cellToChange">Talk to me</TD>
</TR></TBODY></TABLE>
</div>

<script type="text/javascript">
document.getElementById("cellToChange").innerText = "Go on, talk to me please!";
</script>

本文标签: How to change HTML element value using javascriptStack Overflow