How do I replace text inside a div element?
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:
- It only uses the DOM, so the technique is portable to other languages, and doesn't rely on the non-standard innerHTML
- fieldName might contain HTML, which could be an attempted XSS attack. If we know it's just text, we should be creating a text node, instead of having the browser parse it for HTML
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.
You can simply use:
fieldNameElement.innerHTML = "My new text!";
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");
- Element.update documentation
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";