202

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
126k113 gold badges442 silver badges545 bronze badges
asked Sep 23, 2008 at 15:39
2
  • Does the accepted answer do what you want it to when assigned text like is:- <span style="font-size:36pt">This is big</span>. If this behaviour is desirable then can you re-phrase the question to match? Commented Sep 23, 2008 at 16:13
  • Could this be used in a XSS injection attack? Commented May 4, 2012 at 11:15

13 Answers 13

283

You can simply use:

fieldNameElement.innerHTML = "My new text!";
answered Sep 23, 2008 at 15:41
Sign up to request clarification or add additional context in comments.

5 Comments

Shouldn't single quotes be used for 'static' text?
In PHP, yes. In JavaScript, I don't believe it matters.
In Javascript, single and double quotes are interchangeable.
bad advice, because the text may contain HTML-markup-like content by accident
element.innerHTML = "<script>doSomethingMalicious()</script>";won't be a good idea. element.innerHTML = "& neither will this";
228

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 .textContent(), a standard method is provided in all current browsers.

fieldNameElement.textContent = "New text";
answered Sep 10, 2013 at 15:30

3 Comments

@Legolas Hence writing 'current browser' two years ago.
Thank you! I was trying the other answers, wondering why 'innerHTML' wasn't working.
You might consider elaborating on why textContent is a superior method to innerHTML: it's faster, safer, and more appropriate when not deliberately trying to insert HTML markup.
79

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.

answered Sep 23, 2008 at 15:52

6 Comments

Which other languages could you port this technique to?
Any language with a DOM implementation supports this (and most languages have a DOM implementation).
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
I borrowed fieldName and the ID from the question itself.
The question probably used field_name to make the example generic. Also the questioner mentions that Prototype is available but not jQuery.
|
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");
answered Sep 23, 2008 at 15:46

4 Comments

@Aeyoun The OP implied they were already using Prototype, so if that's the case it makes sense to take advantage of it.
Why to me only works with $("field_name").text("new text");
@Drako Are you using PrototypeJS?
@Drako The original question and my answer from seven years ago are for PrototypeJS not jQuery.
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.

answered Sep 23, 2008 at 15:41

6 Comments

That doesn't look like JavaScript?
Don't use innerHTML. It's not a w3c recommendation and behaves inconsistently. It's considered bad style.
Tom, what should be used instead (if you don't use Prototype)?
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.
@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. api.prototypejs.org/dom/dollar
|
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.

answered Sep 23, 2008 at 15:48

Comments

7

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

if (fieldNameElement)
 fieldNameElement.innerHTML = 'some HTML';
answered Sep 23, 2008 at 15:41

Comments

7

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";
}
answered Jul 26, 2010 at 21:17

Comments

4
el.innerHTML='';
el.appendChild(document.createTextNode("yo"));
answered Nov 24, 2011 at 17:07

Comments

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.");

answered Sep 23, 2008 at 15:53

1 Comment

Prototype has similar utility functions.
2

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

answered May 27, 2018 at 3:49

Comments

0
function showPanel(fieldName) {
 var fieldNameElement = document.getElementById(field_name);
 fieldNameElement.removeChild(fieldNameElement.firstChild);
 var newText = document.createTextNode("New Text");
 fieldNameElement.appendChild(newText);
}
answered Sep 23, 2008 at 15:47

1 Comment

Better to replace the node then to remove it and add a new one as two separate operations.
0

Here's an easy jQuery way:

var el = $('#yourid .yourclass');
el.html(el.html().replace(/Old Text/ig, "New Text"));
alonisser
12.2k21 gold badges89 silver badges144 bronze badges
answered Feb 24, 2010 at 13:22

2 Comments

This seems like a bad idea - what if your element contained subnodes with the same text, or your text matched part of an element tag name? WHy not just use .text?
I completely agree with James Westgate, should not do that.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.