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 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"

本文标签: