1

Why innerHTML gives me "2 #2 " and innerText "2 #2"? the space is missed.

I believed innerText would gave me "2 #2 " as innerHTML too. image

Just want to know the difference(if there is any difference) for this context, i know innerHTML is different, but is just text.

Chris Barr
  • 29,851
  • 23
  • 95
  • 135
Sr.Jose
  • 13
  • 6

1 Answers1

0

So you are concerned why an extra space in one and not the other.

It can be easily reproduced by:

const el = document.querySelector("#msg");

console.log(JSON.stringify(el.innerText));
console.log(JSON.stringify(el.innerHTML));
console.log(JSON.stringify(el.textContent));
<div id="msg">hi there </div>

You can see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText

As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.

so the space is not rendered according to the rules of HTML, and that's why innerText doesn't have the space at the end.

If your HTML is

<div id="msg">
  hi there     
</div>

and with 5 spaces after the word there, the newline and spaces are all not rendered, so innerText would not give you those either.

You can also compare that to textContent, as quoted on the page above:

Note: innerText is easily confused with Node.textContent, but there are important differences between the two. Basically, innerText is aware of the rendered appearance of text, while textContent is not.

You also can guess what the following will give out:

const el = document.querySelector("#msg");

console.log(JSON.stringify(el.innerText));
console.log(JSON.stringify(el.innerHTML));
console.log(JSON.stringify(el.textContent));
<div id="msg">hi    there </div>

So the answer is: when rendered, the spaces are collapsed together, so innerText gives you that version, while the other faithfully give you the one with multiple spaces.

pokemon
  • 18
  • 1