Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 375
Amra Avatar asked Jan 29 '10 17:01

Amra


People also ask

Can TD tag have ID?

An id on a <td> tag assigns an identifier to the table cell. The identifier must be unique across the page.

How do I add text to a table in HTML?

The <caption> tag must be inserted immediately after the <table> tag. Tip: By default, a table caption will be center-aligned above a table. However, the CSS properties text-align and caption-side can be used to align and place the caption.

How do you add a paragraph in Javascript?

Use the insertAdjacentText() method to append text to a paragraph element, e.g. p. insertAdjacentText('beforeend', 'my text') . The method inserts a new text node at the provided position, relative to the element it was called on.

Can TD element have a value?

td elements don't have value. What you are looking for is to get the value of the attribute value of that element.


2 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> 
like image 172
artlung Avatar answered Sep 21 '22 02:09

artlung


append a text node as follows

var td1 = document.getElementById('td1'); var text = document.createTextNode("some text"); td1.appendChild(text); 
like image 31
Jonathan Fingland Avatar answered Sep 22 '22 02:09

Jonathan Fingland