You can simply use:
fieldNameElement.innerHTML = "My new text!";
Updated for everyone reading this in 2013 and later:
This answer has a lot of SEO, but all the answers are severely out of date and depend on libraries to do things that all current browsers do out of the box.
To replace text inside a div element, use Node.textContent, which is provided in all current browsers.
fieldNameElement.textContent = "New text";
function showPanel(fieldName) {
var fieldNameElement = document.getElementById("field_name");
while(fieldNameElement.childNodes.length >= 1) {
fieldNameElement.removeChild(fieldNameElement.firstChild);
}
fieldNameElement.appendChild(fieldNameElement.ownerDocument.createTextNode(fieldName));
}
The advantages of doing it this way:
If I were going to use a javascript library, I'd use jQuery, and do this:
$("div#field_name").text(fieldName);
Note that @AnthonyWJones' comment is correct: "field_name" isn't a particularly descriptive id or variable name.
I would use Prototype's update
method which supports plain text, an HTML snippet or any JavaScript object that defines a toString
method.
$("field_name").update("New text");
$('field_name').innerHTML = 'Your text.';
One of the nifty features of Prototype is that $('field_name')
does the same thing as document.getElementById('field_name')
. Use it! :-)
John Topley's answer using Prototype's update
function is another good solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With