I found this weird behavior of HTMLelement.innerText
that I can't understand.
Here is an example of the question:
// HTML
<div>
<article id="editor"></article>
</div>
// JavaScript
var editor = document.getElementById('editor');
console.log(editor.innerHTML); // prints "\n"
// From 3rd party libraries
var jqueryExample = jquery.parseHTML('<div><article></article></div>')[0];
console.log(jqueryExample.innerHTML); // prints ""
var angularjsExample = angular.element('<div><article></article></div>')[0];
console.log(angularjsExample.innerHTML); // prints ""
As you see, when I use document.getElementById
, element's innerHTML
has \n
for some reason. However, if I use jquery.parseHTML
or angular.element
, it doesn't add \n
and it returns as it is.
It is more interesting if the HTML has more content:
// HTML
<div>
<article id="editor">
<h1>Test</h1>
<p>Foo</p>
</article>
</div>
// JavaScript
var editor = document.getElementById('editor');
console.log(editor.innerText); // prints "Test\nFoo"
But jquery.parseHTML
and angular.element
's innerText
prints TestFoo
. Why is that???
From the Docs:1
The
innerText
property of the HTMLElement interface represents the "rendered" text content of a node and its descendants. 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.
On my browser (Chrome 61), I see it insert two newlines in the string:
var editor = document.getElementById('editor');
console.log(editor.innerText); // prints "Test\nFoo"
console.log(editor.innerText.length);
console.log(Array.from(editor.innerText))
<script src="//unpkg.com/angular/angular.js"></script>
<div>
<article id="editor">
<h1>Test</h1>
<p>Foo</p>
</article>
</div>
It does not add any new lines. It just outputs contents “as is”. In first case, it outputs an empty character, so you do not see it. In the second case, there are four new lines (check below the editor-2
example about how to output same content as single line).
var editor1 = document.getElementById('editor-1');
console.log('editor-1: [' + editor1.innerHTML + ']'); //-> "[]"
var editor2 = document.getElementById('editor-2');
console.log('editor-2: [' + editor2.innerHTML + ']'); //-> "[<h1>Test</h1><p>Foo</p>]"
<div>
<article id="editor-1"></article>
<article id="editor-2"><h1>Test</h1><p>Foo</p></article>
</div>
That's not a problem with getElementById
(that's just a method to get the element). You are doing different things. the getElementById
finds an element rendered by the browser, angular an jquery code are creaing a new element so it may be different than the first element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With