20

I need to change the text inside HTML element using javascript, but I have no idea about how to do it. ¿Any help?

I've got it defined like:

<h2 id="something">Text I want to change.</h2>

Im trying to do it with:

document.getElementById("something").value = "new text";

But it doesn't work.

Thanks

asked Apr 24, 2014 at 16:10
1
  • 1
    You should use jQuery for that, it works everywhere. Commented Apr 24, 2014 at 16:12

3 Answers 3

31

You can use innerHTML :

document.getElementById("something").innerHTML = "new text";
answered Apr 24, 2014 at 16:11
Sign up to request clarification or add additional context in comments.

Comments

13

If the element only contains text, textContent works better and faster than innerHTML

document.getElementById("something").textContent = 'new text';

Good luck :)

answered Apr 24, 2014 at 16:38

Comments

4

Though the following code would be the fastest alternative to slow .innerHTML:

var element = document.getElementById('something');
// removing everything inside the node
while (element.firstChild) {
 element.removeChild(element.firstChild);
}
// appending new text node
element.appendChild(document.createTextNode('new text'));

And here is the benchmark:

JSPerf

JSPerf: http://jsperf.com/replace-text-in-node

answered Apr 24, 2014 at 16:22

1 Comment

(just for info) You can also remove all child nodes with element.textContent = ''; ... textContent on its own (as in my suggestion) performs well JSPref

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.