Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 402
Carol Avatar asked Apr 24 '14 16:04

Carol


People also ask

How can we change text element?

Use the textContent property to change the text of an element, e.g. element. textContent = 'New text' . The textContent property will set the text of the element to the provided string, replacing any of the existing content. Here is the HTML for the examples in this article.

What is H2 in JavaScript?

An H2 tag marks the first sub-heading after your document's main heading. It defines the second-level headings on your webpage. Like an H1 tag, an H2 tag also appears larger than the rest of your main body text.

Can JavaScript change HTML?

The HTML DOM allows JavaScript to change the content of HTML elements.


2 Answers

You can use innerHTML:

document.getElementById("something").innerHTML = "new text";
like image 154
Felix Avatar answered Sep 19 '22 03:09

Felix


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

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

Good luck :)

like image 20
erosman Avatar answered Sep 18 '22 03:09

erosman