替代innerHTML?

发布于 2024-07-16 14:20:49 字数 601 浏览 3 评论 0原文

编辑:哇。 这个问题已经12年了。

正如有人所说,自 2016 年以来,这可以通过一行完成: https://stackoverflow.com/a/69322509/80907< /a>


原文:

我想知道是否有一种方法可以在不使用innerHTML 的情况下更改HTML 中任何内容的文本。

我之所以问这个问题,是因为 W3C 对此有点不满。 我知道这很挑剔,但我只是想知道,有什么办法吗?

编辑:人们似乎误解了我在这里问的问题:我想找到一种方法来有效地更改正在显示的文本。

如果我有:

<div id="one">One</a>

innerHTML 允许我这样做:

var text = document.getElementsById("one");
text.innerHTML = "Two";

并且屏幕上的文本将会改变。
我不想附加更多文本,我希望更改现有文本。

EDIT: WOW. This question is 12 years old now.

As someone stated, it can be done with a one-liner since 2016: https://stackoverflow.com/a/69322509/80907


The original:

I'm wondering if there's a way to change the text of anything in HTML without using innerHTML.

Reason I'm asking is because it's kinda frowned upon by the W3C.
I know it's nitpicking, but I just wanna know, is there a way?

EDIT: people seem to misunderstand what I'm asking here: I want to find a way to effectivly change the text being displayed.

If I have:

<div id="one">One</a>

innerHTML allows me to do this:

var text = document.getElementsById("one");
text.innerHTML = "Two";

And the text on my screen will have changed.
I do not wish to append more text, I wish to change allready existing text.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

梦中楼上月下 2024-07-23 14:20:49

推荐的方法是通过 DOM 操作,但它可能非常冗长。 例如:

// <p>Hello, <b>World</b>!</p>
var para = document.createElement('p');
para.appendChild(document.createTextNode('Hello, '));

// <b>
var b = document.createElement('b');
b.appendChild(document.createTextNode('World');
para.appendChild(b);

para.appendChild(document.createTextNode('!'));

// Do something with the para element, add it to the document, etc.

编辑

为了响应您的编辑,为了替换当前内容,您只需删除现有内容,然后使用上面的代码填充新内容即可。 例如:

var someDiv = document.getElementById('someID');
var children = someDiv.childNodes;
for(var i = 0; i < children.length; i++)
    someDiv.removeChild(children[i]);

但正如其他人所说,我建议使用 jQuery 之类的东西,因为并非所有浏览器都完全支持 DOM,并且那些确实有一些怪癖的浏览器由 JavaScript 库在内部处理。 例如,jQuery 看起来像这样:

$('#someID').html("<p>Hello, <b>World</b>!</p>");

The recommended way is through DOM manipulation, but it can be quite verbose. For example:

// <p>Hello, <b>World</b>!</p>
var para = document.createElement('p');
para.appendChild(document.createTextNode('Hello, '));

// <b>
var b = document.createElement('b');
b.appendChild(document.createTextNode('World');
para.appendChild(b);

para.appendChild(document.createTextNode('!'));

// Do something with the para element, add it to the document, etc.

EDIT

In response to your edit, in order to replace the current content, you simply remove the existing content, then use the code above to fill in new content. For example:

var someDiv = document.getElementById('someID');
var children = someDiv.childNodes;
for(var i = 0; i < children.length; i++)
    someDiv.removeChild(children[i]);

But as someone else said, I'd recommend using something like jQuery instead, as not all browsers fully support DOM, and those that do have quirks which are dealt with internally by JavaScript libraries. For example, jQuery looks something like this:

$('#someID').html("<p>Hello, <b>World</b>!</p>");
云仙小弟 2024-07-23 14:20:49

The better way of doing it is to use document.createTextNode. One of the main reasons for using this function instead of innerHTML is that all HTML character escaping will be taken care of for you whereas you would have to escape your string yourself if you were simply setting innerHTML.

清风挽心 2024-07-23 14:20:49

通过操作 DOM 可以获得相同的效果。 更改文本最安全的方法是删除该元素的所有子节点并用新的文本节点替换它们。

var node = document.getElementById("one");

while( node.firstChild )
    node.removeChild( node.firstChild );
node.appendChild( document.createTextNode("Two") );

删除子节点会删除元素的文本内容,然后再将其替换为新文本。

大多数开发人员避免使用innerHTML 的原因是通过DOM 访问元素是符合标准的。

You can get the same effect by manipulating the DOM. The safest way to change text is to remove all the child nodes of the element and replace them with a new text node.

var node = document.getElementById("one");

while( node.firstChild )
    node.removeChild( node.firstChild );
node.appendChild( document.createTextNode("Two") );

Removing the child nodes gets rid of the text content of your element before replacing it with the new text.

The reason most developers avoid using innerHTML is that accessing elements through the DOM is standards compliant.

一抹苦笑 2024-07-23 14:20:49

如果您只想更改纯文本,那么有一个更快的依赖标准的解决方案:

document.getElementById("one").firstChild.data = "two";

无论如何,请注意,innerHTML 将成为即将推出的 HTML 5 标准的一部分。

If you only want to change plain text, then there's a quicker solution that relies on standards:

document.getElementById("one").firstChild.data = "two";

Anyway, please note that innerHTML is going to be part of the upcoming HTML 5 standard.

流绪微梦 2024-07-23 14:20:49

简单的。

text.innerHTML = 'two' 替换为 text.firstChild.nodeValue = 'two'

Simple.

Replace text.innerHTML = 'two' with text.firstChild.nodeValue = 'two'.

守护在此方 2024-07-23 14:20:49

还在寻找绕过 element.innerHTML 的良好替代方案,我终于找到了解决方案:

HTMLElement.prototype.htmlContent = function(html)
{
    var dom = new DOMParser().parseFromString('<template>'+html+'</template>', 'text/html').head;
    this.appendChild(dom.firstElementChild.content);
}

//-- document.getElementById('my-id').innerHTML = string_of_html;
document.getElementById('my-id').htmlContent(string_of_html);

另一种没有

HTMLElement.prototype.htmlContent = function(html)
{
    var dom = new DOMParser().parseFromString(html, 'text/html').body;
    while (dom.hasChildNodes()) this.appendChild(dom.firstChild);
}

请记住,当innerHTML“替换”内容时,此方法实际上“添加”内容...

这可能有帮助:

HTMLElement.prototype.clearContent = function()
{
    while (this.hasChildNodes()) this.removeChild(this.lastChild);
}

//-- document.getElementById('my-id').innerHTML = '';
document.getElementById('my-id').clearContent();

doc:https://github.com/swannty/escaping-innerHTML

性能: https://jsperf.com/escaping-innerhtml

Also looking for a good alternative to bypass element.innerHTML I finally found that solution:

HTMLElement.prototype.htmlContent = function(html)
{
    var dom = new DOMParser().parseFromString('<template>'+html+'</template>', 'text/html').head;
    this.appendChild(dom.firstElementChild.content);
}

//-- document.getElementById('my-id').innerHTML = string_of_html;
document.getElementById('my-id').htmlContent(string_of_html);

Another alternative without <template> tags, but loop instead:

HTMLElement.prototype.htmlContent = function(html)
{
    var dom = new DOMParser().parseFromString(html, 'text/html').body;
    while (dom.hasChildNodes()) this.appendChild(dom.firstChild);
}

Keep in mind that this method actually 'add' content when innerHTML 'replace' content...

This may help:

HTMLElement.prototype.clearContent = function()
{
    while (this.hasChildNodes()) this.removeChild(this.lastChild);
}

//-- document.getElementById('my-id').innerHTML = '';
document.getElementById('my-id').clearContent();

doc: https://github.com/swannty/escaping-innerHTML

perf: https://jsperf.com/escaping-innerhtml

勿忘初心 2024-07-23 14:20:49

这是一个非常古老的问题。

现在,事情发生了变化:

element.innerText = "Hi There!"

一句台词。
自 2016 年以来,每个浏览器都支持此功能。

This is a very old question.

Now, things changed:

element.innerText = "Hi There!"

A one-liner.
Since 2016 every single browser supports this.

话少情深 2024-07-23 14:20:49
var who=document.getElementById('one'), txt='new text';
if(who.innerText) who.innerText=txt;
else if(who.textContent) who.textContent= txt;

这可能与innerHTML一样令您反感,但它的优点是可以在某些情况下工作(IE),而innerHTML或appendChild不能,例如某些表节点,样式和脚本元素的文本以及表单字段的值

var who=document.getElementById('one'), txt='new text';
if(who.innerText) who.innerText=txt;
else if(who.textContent) who.textContent= txt;

This may be as objectionable as innerHTML to you, but it has the advantage of working in some cases (IE) where innerHTML or appendChild do not, like some table nodes, the text of style and script elements and the value of form fields

为人所爱 2024-07-23 14:20:49

您可以按如下方式使用 DOM:

<html>
<body>
<div>before</div>
<script type="text/javascript">
var element = document.getElementsByTagName("div")[0];
alert(element.firstChild.nodeValue);
element.removeChild(element.firstChild);
element.appendChild(document.createTextNode('after'));
alert(element.firstChild.nodeValue);
</script>
</body>

但我认为很少有人这样做,而是使用像 jQueryPrototype 或任何其他 javascript 框架 那里 代替。 这是 jquery 的例子:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</head>
<body>
<div>before</div>
<script type="text/javascript">
var element = $("div");
alert(element.text());
element.text("after");
alert(element.text());
</script>
</body>

You could use DOM as follows:

<html>
<body>
<div>before</div>
<script type="text/javascript">
var element = document.getElementsByTagName("div")[0];
alert(element.firstChild.nodeValue);
element.removeChild(element.firstChild);
element.appendChild(document.createTextNode('after'));
alert(element.firstChild.nodeValue);
</script>
</body>

But I think anyone rarely do this but use a framework like jQuery or Prototype or any other javascript framework out there instead. This is jquery example:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</head>
<body>
<div>before</div>
<script type="text/javascript">
var element = $("div");
alert(element.text());
element.text("after");
alert(element.text());
</script>
</body>
梦明 2024-07-23 14:20:49

在我看来,CSS+HTML+JS 组合应该能达到预期的效果:

.myelement:before {   
    content: attr(alt);
} 

...

<span class='myelement' alt='initial value'></span> 

...

element.setAttribute('alt', 'new value'); 

有谁知道这在实践中是否有效?

It appears to me that the CSS+HTML+JS combination should achieve desired effects:

.myelement:before {   
    content: attr(alt);
} 

...

<span class='myelement' alt='initial value'></span> 

...

element.setAttribute('alt', 'new value'); 

Does anyone know if this works in practice?

oО清风挽发oО 2024-07-23 14:20:49

好吧,如果正确理解你的问题,这应该是一个答案。

var text = document.getElementById("one");
//text.innerHTML = "Two";
 text.childNodes[0].nodeValue="two";

Well i f i understand your question properly this should be an answer.

var text = document.getElementById("one");
//text.innerHTML = "Two";
 text.childNodes[0].nodeValue="two";
眼趣 2024-07-23 14:20:49

insertAdjacentHTML() 是要走的路。 阅读更多:
点击查看文档

insertAdjacentHTML() is the way to go. Read more:
Click for documentation

黑寡妇 2024-07-23 14:20:49

有时,如果我要定期更新文本节点,我发现存储对文本节点的直接引用很有帮助。 我做了这样的事情:

var dynamicText = myDiv.appendChild(document.createTextNode("the initial text"));

然后每当我需要更新它时,我就这样做:

dynamicText.nodeValue = "the updated text";

这可以避免遍历 DOM 或添加或删除任何子项。

I sometimes find it helpful to store a direct reference to the text node if I am going to be updating it regularly. I do something like this:

var dynamicText = myDiv.appendChild(document.createTextNode("the initial text"));

And then whenever I need to update it, I just do this:

dynamicText.nodeValue = "the updated text";

This prevents having to walk the DOM or add or remove any children.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文