Why does changing innerText value also changes innerHTML?

我们两清 提交于 2021-01-28 23:12:32

问题


I have a asp.net code that creates a button as follows:

<a href="#" id="button1" title="Maximize" onclick="function1('span1')" class="button"><span id="span1" class="iconMaximizeLightText">Maximize</span></a>

now in the javascript file I am doing the following inside the function1 function:

document.getElementById("button1").innerText = "Minimize";
document.getElementById("button1").value = "Minimize";
document.getElementById("button1").className = "iconMinimizeLightText";

What I noticed was before the line : "document.getElementById("button1").innerText = "Minimize";" is executed the value in "document.getElementById("button1").innerHTML" is

document.getElementById("button1").innerHTML = "<span id=span1 class=iconMaximizeLightText>Maximize</span>"

but after that line is executed the value in "document.getElementById("button1").innerHTML" is

document.getElementById("button1").innerHTML = "Minimize"

Why is innerHTML value changing as I only changed the innerText value ?

Thanks in advance.

P.S. Sorry this might be a stupid question but I have only started learning this language since a couple of weeks.


回答1:


Both innerText and innerHTML set the HTML of the element. The difference is that innerText—by the way, you might want to use textContent instead—will escape the string so that you can't embed HTML content in it.

So for example, if you did this:

var div = document.createElement('DIV');
div.innerText = '<span>Hello</span>';
document.body.appendChild(div);

Then you'd actually see the string "<span>Hello</span>" on the screen, as opposed to "Hello" (inside a span).

There are some other subtleties to innerText as well, which are covered in the MDN article referenced above.



来源:https://stackoverflow.com/questions/21999375/why-does-changing-innertext-value-also-changes-innerhtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!