admin管理员组文章数量:1391999
I know it may be a simple thing, but I can't figure out. I am trying to insert some text coming from a JavaScript function onload event into a td.
<html>
<head>
<script type="text/javascript">
function insertText ()
{
//function to insert any text on the td with id "td1"
}
</script>
</head>
<body onload="javascript:insertText()">
<table>
<tr>
<td id="td1">
</td>
</tr>
</table>
</body>
</html>
Any help?
I know it may be a simple thing, but I can't figure out. I am trying to insert some text coming from a JavaScript function onload event into a td.
<html>
<head>
<script type="text/javascript">
function insertText ()
{
//function to insert any text on the td with id "td1"
}
</script>
</head>
<body onload="javascript:insertText()">
<table>
<tr>
<td id="td1">
</td>
</tr>
</table>
</body>
</html>
Any help?
Share Improve this question edited Jul 23, 2017 at 15:32 Brett DeWoody 62.7k31 gold badges144 silver badges191 bronze badges asked Jan 29, 2010 at 17:00 AmraAmra 25.2k28 gold badges85 silver badges93 bronze badges 1- Make sure that the second <body> tag is actually </body>, and the same with the closing </script> tag. Maybe that's just a typo when you put it into the question, but you never know. – David Kolar Commented Jan 29, 2010 at 17:14
5 Answers
Reset to default 100<html>
<head>
<script type="text/javascript">
function insertText () {
document.getElementById('td1').innerHTML = "Some text to enter";
}
</script>
</head>
<body onload="insertText();">
<table>
<tr>
<td id="td1"></td>
</tr>
</table>
</body>
</html>
append a text node as follows
var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);
There are several options... assuming you found your TD by var td = document.getElementyById('myTD_ID');
you can do:
td.innerHTML = "mytext";
td.textContent= "mytext";
td.innerText= "mytext";
- this one may not work outside IE? Not sureUse firstChild or children array as previous poster noted.
If it's just the text that needs to be changed, textContent is faster and less prone to XSS attacks (https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent)
If your <td>
is not empty, one popular trick is to insert a non breaking space
in it, such that:
<td id="td1"> </td>
Then you will be able to use:
document.getElementById('td1').firstChild.data = 'New Value';
Otherwise, if you do not fancy adding the meaningless  
you can use the solution that Jonathan Fingland described in the other answer.
Use jQuery
Look how easy it would be if you did.
Example:
$('#td1').html('hello world');
本文标签: htmlHow to insert text in a td with idusing JavaScriptStack Overflow
版权声明:本文标题:html - How to insert text in a td with id, using JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736953811a1957525.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论