'How to overwrite text in <p> tag using JavaScript

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?



Solution 1:[1]

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

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

instead

Solution 2:[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.

Solution 3:[3]

Using JavaScript

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

You can also use Jquery

$('#replace-me').html('Anything you want')

Solution 4:[4]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sujit Agarwal
Solution 3
Solution 4 Jeremy-F