25

I want to replace the content of a <p> tag only with Vanilla JavaScript. I have something like

<div
    className='container'>
    <p
        className='element' id='replace-me'></p>
</div>

And then I have a function like this

setInterval(function () {
    ...
    document.getElementById('replace-me').innerText(someVar)

}, 1000);

That gives me the error:

TypeError: document.getElementById(...).innerText is not a function

Why is that?

four-eyes
  • 10,740
  • 29
  • 111
  • 220
  • 1
    It's not a function. You need to use it like this: `document.getElementById('replace-me').innerText = someVar;` – Clujio Aug 30 '18 at 13:06
  • 1
    Same question [here](https://stackoverflow.com/questions/37951999/error-message-innerhtml-is-not-a-function/37952034) – dungmidside Aug 30 '18 at 13:06

4 Answers4

44

That's because innerText is an attribute so you should do :

document.getElementById('replace-me').innerText = someVar

instead

jonatjano
  • 3,576
  • 1
  • 15
  • 20
5

Using JavaScript

document.getElementById('replace-me').innerText = 'Anything you want'

You can also use Jquery

$('#replace-me').html('Anything you want')
Lucas
  • 275
  • 8
  • 37
  • 2
    The OP asked a question that is in plain JS, not in jQuery. – Sujit Agarwal Aug 30 '18 at 13:10
  • 1
    I dont wanna use jQuery. I thing using jQuery for a simple selector is a little bit too much :) – four-eyes Aug 30 '18 at 13:12
  • I find OP questions can frequently enrich the learning of those of us who love to learn. For example, while @Lucas response #1 will satisfy, it does not allow the ability to add, for example, an a tag with classes. However, because he took the time to add the Jquery method, I was successful in replacing not only the text, but the entire HTML string (code including a tags and classes) to make the replace function more robust. Thank you. – ND_Coder Sep 26 '22 at 18:11
2

In addition to jonatjano's answer, I'd like to add an alternative.

Just an alternative to innerText is innerHTML -

document.getElementById("demo").innerHTML = "Paragraph changed!";

innerText retrieves and sets the content of the tag as plain text, whereas innerHTML retrieves and sets the same content but in HTML format.

Sujit Agarwal
  • 12,348
  • 11
  • 48
  • 79
1

Try with querySelector (Javascript querySelector vs. getElementById)

paragraph = document.querySelector("#replace-me");
paragraph.innerText = "Your HTML Code";

If it still does not work, check that the element you want is selected.

JavaScript: querySelector Null vs querySelector

Jeremy-F
  • 93
  • 6
  • `paragraph.innerHTML = "Your HTML Code" ` or `paragraph.innerText = "Your PlainText" ` – s3c Jul 20 '20 at 13:09