简体   繁体   English

如何使用JavaScript更改HTML元素值?

[英]How to change HTML element value using javascript?

I have DIV and inside div it has table. 我有DIV,在div里面有桌子。 I want to change the one of the column value of table using java script. 我想使用Java脚本更改表的列值之一。 I can do it by getting the element id of column, but there is no any id assigned to any table's column. 我可以通过获取列的元素ID来做到这一点, 但是没有任何ID分配给任何表的列。 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? 是否可以使用javascript更改“与我交谈”文本?

Yes, you need to get the element and then set a new value to element.innerHTML . 是的,您需要获取元素,然后将新值设置为element.innerHTML It's easiest if you give an id to the element that you want to change but you don't need to 如果为要更改的元素提供一个id ,但又不需要更改id ,这是最简单的

jsFiddle 的jsfiddle

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

If your userbase is IE8+, you can safely use querySelector : 如果您的用户群是IE8 +,则可以安全地使用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.net/rgthree/YkhwE/ 这是一个JSFIDDLE: http : //jsfiddle.net/rgthree/YkhwE/

querySelector (or querySelectorAll ) allow you to target elements in the DOM via CSS syntax, which is very useful. querySelector (或querySelectorAll )使您可以通过CSS语法将DOM中的元素作为目标,这非常有用。 It's very well supported, in every current and previous browser. 在每个当前和以前的浏览器中,它都受到很好的支持。 (via Can I Use ) (通过我可以使用

You can assign an id to the TD, and use that; 您可以为TD分配一个ID,然后使用该ID。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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