196

I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available.

<div id="panel">
  <div id="field_name">TEXT GOES HERE</div>
</div>

Here's what the function will look like:

function showPanel(fieldName) {
  var fieldNameElement = document.getElementById('field_name');
  //Make replacement here
}
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
sblundy
  • 60,628
  • 22
  • 121
  • 123

14 Answers14

278

You can simply use:

fieldNameElement.innerHTML = "My new text!";
Community
  • 1
  • 1
17 of 26
  • 27,121
  • 13
  • 66
  • 85
222

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";
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
78

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.

Community
  • 1
  • 1
Daniel Papasian
  • 16,145
  • 6
  • 29
  • 32
  • Which other languages could you port this technique to? – John Topley Sep 23 '08 at 15:54
  • Any language with a DOM implementation supports this (and most languages have a DOM implementation). – Quentin Sep 23 '08 at 16:01
  • This is good answer, better than mine and is the correct answer. You might consider tidying the example though. 'fieldname' is not a good name for the function's parameter. In fact it might be best to take two one for the element ID and another for the content, i.e.; elemID, content – AnthonyWJones Sep 23 '08 at 16:07
  • I borrowed fieldName and the ID from the question itself. – Daniel Papasian Sep 23 '08 at 17:00
  • The question probably used field_name to make the example generic. Also the questioner mentions that Prototype is available but not jQuery. – John Topley Sep 23 '08 at 17:13
  • Note `textContent` achieves the same easily, `innerHTML` is now standard, and you can use `document` instead of `fieldNameElement.ownerDocument`. – Oriol Apr 02 '16 at 15:11
52

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");
John Topley
  • 113,588
  • 46
  • 195
  • 237
18
$('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.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
  • 5
    That doesn't look like JavaScript? – Milan Babuškov Sep 23 '08 at 15:42
  • 1
    Don't use innerHTML. It's not a w3c recommendation and behaves inconsistently. It's considered bad style. – Tom Sep 23 '08 at 15:54
  • Tom, what should be used instead (if you don't use Prototype)? – Milan Babuškov Sep 23 '08 at 16:19
  • 1
    Milan, the more accepted way is to loop through the childNodes, call removeNode(true) on each, then append new nodes created using document.createElement() or document.createTextNode(). If you need to do that I would recommend writing a function to avoid a lot of typing. – Joel Anair Sep 24 '08 at 15:13
  • you forgot the #. it's $('#field_name') actually – Radu Simionescu Oct 14 '12 at 23:56
  • 3
    @RaduSimionescu No, it isn't. This question and answer is about Prototype.js, not jQuery. In Prototype `$` looks up an item by ID. It's not selector-based like jQuery is. http://api.prototypejs.org/dom/dollar/ – ceejayoz Oct 15 '12 at 02:11
18

The quick answer is to use innerHTML (or prototype's update method which pretty much the same thing). The problem with innerHTML is you need to escape the content being assigned. Depending on your targets you will need to do that with other code OR

in IE:-

document.getElementById("field_name").innerText = newText;

in FF:-

document.getElementById("field_name").textContent = newText;

(Actually of FF have the following present in by code)

HTMLElement.prototype.__defineGetter__("innerText", function () { return this.textContent; })

HTMLElement.prototype.__defineSetter__("innerText", function (inputText) { this.textContent = inputText; })

Now I can just use innerText if you need widest possible browser support then this is not a complete solution but neither is using innerHTML in the raw.

AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
7

If you really want us to just continue where you left off, you could do:

if (fieldNameElement)
    fieldNameElement.innerHTML = 'some HTML';
Milan Babuškov
  • 59,775
  • 49
  • 126
  • 179
6

nodeValue is also a standard DOM property you can use:

function showPanel(fieldName) {
  var fieldNameElement = document.getElementById(field_name);
  if(fieldNameElement.firstChild)
    fieldNameElement.firstChild.nodeValue = "New Text";
}
palswim
  • 11,856
  • 6
  • 53
  • 77
4
el.innerHTML='';
el.appendChild(document.createTextNode("yo"));
Adrian Adkison
  • 3,537
  • 5
  • 33
  • 36
2

If you're inclined to start using a lot of JavaScript on your site, jQuery makes playing with the DOM extremely simple.

http://docs.jquery.com/Manipulation

Makes it as simple as: $("#field-name").text("Some new text.");

Steve Perks
  • 5,490
  • 3
  • 28
  • 41
2

Use innerText if you can't assume structure - Use Text#data to update existing text Performance Test

Youth overturn
  • 341
  • 5
  • 7
0
function showPanel(fieldName) {
  var fieldNameElement = document.getElementById(field_name);

  fieldNameElement.removeChild(fieldNameElement.firstChild);
  var newText = document.createTextNode("New Text");
  fieldNameElement.appendChild(newText);
}
hollystyles
  • 4,979
  • 2
  • 36
  • 38
0

Here's an easy jQuery way:

var el = $('#yourid .yourclass');

el.html(el.html().replace(/Old Text/ig, "New Text"));
alonisser
  • 11,542
  • 21
  • 85
  • 139
Cosmin
  • 1
0

In HTML put this

<div id="field_name">TEXT GOES HERE</div>

In Javascript put this

var fieldNameElement = document.getElementById('field_name');
        if (fieldNameElement)
        {fieldNameElement.innerHTML = 'some HTML';}
Trees
  • 1,245
  • 10
  • 20