admin管理员组文章数量:1416631
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.
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.
Share Improve this question asked Apr 10, 2015 at 13:24 KannarKKKannarKK 1,62322 silver badges35 bronze badges1 Answer
Reset to default 5You 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 parison .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"
本文标签:
版权声明:本文标题:javascript - How do I prevent HTML encoding of '&' characters while copying content from a div to the ti 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745252729a2649919.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论