PDA

View Full Version : innerHTML Not Displaying



locbtran
09-18-2011, 02:39 PM
I can't seem to get my innerHTML to display my content.

This works fine, if I was to put it all in one line.

document.getElementById('addedText').innerHTML = '<table><tr><td>'+"My text goes here"+'</tr></td></table>';

If I was to break it up, which I wanted then nothing seem to show up.

document.getElementById('addedText').innerHTML = '<table><tr><td>';
document.getElementById('addedText').innerHTML = "My text goes here";
document.getElementById('addedText').innerHTML = '</tr></td></table>';


Here's my code

<html>
<head>
<script type="text/javascript">
function display() {
document.getElementById('addedText').innerHTML = '<table border=1><tr><td>';
document.getElementById('addedText').innerHTML = "My text goes here";
document.getElementById('addedText').innerHTML = '</tr></td></table>';
}
</script>
</head>

<body onload="display()">
<div id="addedText"></div>
</body>
</html>

thanks

Nile
09-18-2011, 02:44 PM
It's because every time you use the = operator, it just sets the value of innerHTML, it doesn't add onto the current value, or append, so you're actually just setting addedText to "</tr></td></table>". You'd need to do:


document.getElementById('addedText').innerHTML = '<table><tr><td>';
document.getElementById('addedText').innerHTML += "My text goes here";
document.getElementById('addedText').innerHTML += '</tr></td></table>';

jscheuer1
09-18-2011, 08:32 PM
That's the right idea, but could have problems. The browser is allowed to insert missing and close unclosed tags. So after the:


document.getElementById('addedText').innerHTML = '<table><tr><td>';

The browser could have:


<table><tbody><tr><td></td></tr></tbody></table>

Anything added after that would be outside the table. In fact that's what happens in Firefox and IE.

Also, here:



document.getElementById('addedText').innerHTML = '<table><tr><td>';
document.getElementById('addedText').innerHTML += "My text goes here";
document.getElementById('addedText').innerHTML += '</tr></td></table>';

That's invalid. The td needs to close before the tr.

So what you'd really need is:


<script type="text/javascript">
function display() {
var theHTML = '<table border=1><tr><td>';
theHTML += "My text goes here";
theHTML += '</td></tr></table>';
document.getElementById('addedText').innerHTML = theHTML;
}
</script>