javascript - How do I prevent HTML encoding of '&' characters while copying content from a div to the ti

I have a div whose contents are My Home & Administration<div id="abc"> My Home &

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 badges
Add a ment  | 

1 Answer 1

Reset to default 5

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 parison .innerHTML will return "Foo <strong>bar</strong> baz"

Similarly for:

<div id="abc">Foo&amp;Bar</div>

.textContent will be "Foo&Bar", .innerHTML will be "Foo&amp;Bar"

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745252729a4618774.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信