简体   繁体   English

如何覆盖文本<p>使用 JavaScript 标记</p>

[英]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我只想用 Vanilla JavaScript替换<p> tag的内容。我有类似的东西

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

And then I have a function like this然后我有一个这样的 function

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

}, 1000);

That gives me the error:这给了我错误:

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

Why is that?这是为什么?

That's becauseinnerText is an attribute so you should do:那是因为innerText是一个属性,所以你应该这样做:

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

instead反而

Using JavaScript使用 JavaScript

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

You can also use Jquery您也可以使用 Jquery

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

In addition to jonatjano 's answer, I'd like to add an alternative.除了jonatjano的回答,我还想添加一个替代方案。

Just an alternative to innerText is innerHTML - innerText的替代品是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. innerText 检索并设置标签的内容为纯文本,而 innerHTML 检索并设置相同的内容,但格式为 HTML。

Try with querySelector ( Javascript querySelector vs. getElementById )尝试使用 querySelector( Javascript querySelector 与 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 JavaScript:querySelector Null 与 querySelector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM