Change text inside <h2> Text I would change the element </h2> using javascript

I need to change the text inside

HTML element using javascript, but I have no idea how to do this. ΒΏAny help?

I have it defined as:

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

I am trying to do this with

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

But that will not work.

thanks

+8
javascript html
source share
3 answers

You can use innerHTML :

 document.getElementById("something").innerHTML = "new text"; 
+14
source share

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

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

Good luck :)

+5
source share

Although 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 this mark:

Jsperf

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

+3
source share

All Articles