views:

283

answers:

5

I know it may be a simple thing, but I cant 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?

Thanks.

+4  A: 

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.

Daniel Vassallo
For some reason, does not work. :-(
Cesar Lopez
@Cesar: Sorry I had a typo in `getElementById`. Try again now.
Daniel Vassallo
+2  A: 

Use jQuery

Look how easy it would be if you did.

Example:

$('#td1').html('hello world');
gmcalab
Cant use JQuery, but thanks.
Cesar Lopez
@Cesar why not?
gmcalab
+4  A: 

append a text node as follows

var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);
Jonathan Fingland
Thanks for your reply, but it does not work.
Cesar Lopez
@Jonathan: You copied my `document.getElementById('td1');`, all together with my typo :)
Daniel Vassallo
indeed. Thanks for the correction. quicker than typing it, obviously :)
Jonathan Fingland
+2  A: 

There are several options... assuming you found you 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.

DVK
For some reason I get Object doesnt support this property or method.But thanks anyway.
Cesar Lopez
Which one of the 4?
DVK
Any that are preceded by getElement -> y <- ById.
David Kolar
+2  A: 
<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>
artlung