How to insert text in a td with id, using JavaScript

JavascriptHtml

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

append a text node as follows

var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);

Solution 3 - Javascript

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 sure

  • Use 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)

Solution 4 - Javascript

If your <td> is not empty, one popular trick is to insert a non breaking space &nbsp; in it, such that:

 <td id="td1">&nbsp;</td>

Then you will be able to use:

 document.getElementById('td1').firstChild.data = 'New Value';

Otherwise, if you do not fancy adding the meaningless &nbsp you can use the solution that Jonathan Fingland described in the other answer.

Solution 5 - Javascript

Use jQuery

Look how easy it would be if you did.

Example:

$('#td1').html('hello world');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmraView Question on Stackoverflow
Solution 1 - JavascriptartlungView Answer on Stackoverflow
Solution 2 - JavascriptJonathan FinglandView Answer on Stackoverflow
Solution 3 - JavascriptDVKView Answer on Stackoverflow
Solution 4 - JavascriptDaniel VassalloView Answer on Stackoverflow
Solution 5 - JavascriptGabeView Answer on Stackoverflow