I want to replace a span element with the id "randMsg" with the string "saying". Here is what I have right now:
document.getElementById('randMsg').write(saying);
Any ideas? I’m a JavaScript noob, what am I doing wrong?
You can use the textContent property to update the text inside the element:
document.getElementById("randMsg").textContent = "Replaced Content";
Or if you need it to work in IE8 and below, you can detect support for textContent, and if it is not supported, you can use the non-standard innerText instead:
var el = document.getElementById("randMsg"),
msg = "Replaced Content";
("textContent" in el) ? el.textContent = msg : el.innerText = msg;
The following W3C DOM code works in all mainstream browsers, including IE8 and older.
var node = document.getElementById('randMsg');
var textToUse = 'Hello, World!';
// Remove all the children of the node.
while (node.hasChildNodes()) {
node.removeChild(node.firstChild);
}
// Now add the text.
node.appendChild(document.createTextNode(textToUse));
You can also use innerText, however, not supported in Firefox:
node.innerText = textToUse;
Or, you can use textContent, however, not supported by IE versions 8 and older:
node.textContent = textToUse;
Quirksmode has very well maintained browser compatibility tables for all of the above.
You must set the innerHTML property of the element. Consider the following markup:
<span id="randMsg"></span>
And in your JS code:
var saying = 'Say Hello World';
document.getElementById('randMsg').innerHTML = saying;
And your result would be:
<span id="randMsg">Say Hello World</span>
Don't forget to add this script after your element (or wait for DOM ready):
<body>
<span id="randMsg"></span>
<script>
var saying = 'Say Hello World';
document.getElementById('randMsg').innerHTML = saying;
</script>
</body>
innerHTML may not work properly if the text includes characters like < or &. Sounds like you want innerText, which will accept the string as text, but which, of course, lacks Firefox support.
document.getElementById('...').innerHTML = ...document.getElementById('randMsg').innerHTML("saying");$('#randMsg').innerHTML("saying");or some such?