How to overwrite text in <p> tag using JavaScript

Viewed 36704

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?

4 Answers

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

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

instead

Using JavaScript

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

You can also use Jquery

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

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.

Related