Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace text inside a div element?

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:

  1. It only uses the DOM, so the technique is portable to other languages, and doesn't rely on the non-standard innerHTML
  2. 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.


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

$('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.