How to insert text in td with id using javascript

I know this may be simple, but I cannot understand. I am trying to insert some text coming from a JavaScript function load event in 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?

+50
javascript html
Jan 29 '10 at 17:00
source share
5 answers
 <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> 
+55
Jan 29 '10 at 17:17
source share

add node text as follows

 var td1 = document.getElementById('td1'); var text = document.createTextNode("some text"); td1.appendChild(text); 
+28
Jan 29
source share

There are several options: if you found your TD on var td = document.getElementyById('myTD_ID'); , You can do:

  • td.innerHTML = "mytext";

  • td.textContent= "mytext";

  • td.innerText= "mytext"; - it may not work outside of IE? Not sure

  • Use an array of firstChild or children, as the 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 )

+13
Jan 29 '10 at 17:11
source share

If your <td> not empty, one popular trick is to insert unplanned space &nbsp; to:

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

Then you can use:

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

Otherwise, if you do not want to add a meaningless   , you can use the solution that Jonathan Finngland described in another answer .

+4
Jan 29 '10 at 17:04
source share

Use jQuery

See how easy it would be if you did.

Example:

 $('#td1').html('hello world'); 
+2
Jan 29 '10 at
source share



All Articles