如何防止'&'的HTML编码人物从一个div复制内容到页面的标题? [英] How do I prevent HTML encoding of '&' characters while copying content from a div to the title of the page?
问题描述
我有一个div,其内容是My Home&管理
< div id =abc>我的家庭&管理>< / div>
在脚本中,我需要将这个div的内容复制到我的页面标题中。目前我使用的是编码该值的innerHTML属性。
< script type =text / javascript>
var id = document.getElementById(abc);
document.title = id.innerHTML;
< / script>
标题显示为 My Home& amp; Administration
(注意:忽略&和amp;之间的空格)
有没有其他方式显示标题?
我不能使用JQuery或除纯粹和简单的Javascript之外的任何框架
另外请注意,这不是URL编码,而是将字符转换为它们的HTML实体。
.textContent
而不是 .innerHTML
。 .innerHTML
实际上并不是DOM规范的一部分,大多数浏览器都提供它作为非标准功能。 C $ C> .innerHT ML 。
由于您对节点的实际文本值感兴趣,因此您可以使用 .textContent
。
知道 div
abc 实际上在它内部有一个节点,一个 TextNode
,它包含该值。 div
本身实际上并不包含该值。如果您要遍历DOM,您将看到此文本节点。
如果您的HTML为:
< div id =abc> Foo< strong> bar< / strong>巴兹< / DIV>
您的结构将会是:
`div`:abc
TextNode Foo
`strong`
TextNode bar
TextNode baz
在这种情况下, abc.textContent
会返回Foo bar baz
,因此忽略 strong
标记。
比较。
>同样的:
< div id =abc> Foo& amp< / div>
.textContent
将会Foo& Bar
, .innerHTML
将会是Foo& Bar
I have a div whose contents are My Home & Administration
<div id="abc"> My Home & Administration></div>
In the scripts, I need to copy the contents of this div to my page title. Currently I am using innerHTML property which encodes the value.
<script type="text/javascript>
var id = document.getElementById("abc");
document.title = id.innerHTML;
</script>
The title is displayed as My Home & amp; Administration (Note: disregard the space between & and amp;)
Is there any alternate way where the title is displayed as is? I cannot use JQuery or any frameworks apart from pure and simple Javascript
Also note that this is not URL encoding but rather conversion of characters to their HTML entities.
You can use .textContent
instead of .innerHTML
.
.innerHTML
is actually not part of the DOM spec. Most browsers offer it as a non-standard feature. There are several problems with .innerHTML
.
Since you're interested in the actual text value of the node you can use .textContent
.
It might be useful to know that the div
abc actually has a node inside it, a TextNode
, which holds the value. The div
itself doesn't actually hold the value. If you were to traverse the DOM you would see this text node.
If your HTML is:
<div id="abc">Foo <strong>bar</strong> baz</div>
Your structure will be:
`div`:abc
TextNode Foo
`strong`
TextNode bar
TextNode baz
In this case abc.textContent
will return "Foo bar baz"
so it ignores the strong
tag.
In comparison .innerHTML
will return "Foo <strong>bar</strong> baz"
Similarly for:
<div id="abc">Foo&Bar</div>
.textContent
will be "Foo&Bar"
, .innerHTML
will be "Foo&Bar"
这篇关于如何防止'&'的HTML编码人物从一个div复制内容到页面的标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!