Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the innerHTML setter not work correctly with <br> tags?

Why is the new line rendered correctly for real DOM Elements while getting them through innerText, but not considered when I create them using some javascript?

What is wrong with this code snipet?

const real = document.querySelector('p');
const fake = document.createElement('p');
fake.innerHTML = 'foo<br>bar';

console.log(real.innerText); // this is not similar
console.log(real.textContent);
console.log(real.innerHTML);

console.log(fake.innerText); // to this, but why?
console.log(fake.textContent);
console.log(fake.innerHTML);
<p>foo<br>bar</p>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The innerHTML setter works correctly, the issue is in the innerText method which needs layout information to compute the result. Since the fake node is not in the DOM there is no such information so it it just ignores the <br>. Once the node is inserted into DOM the results are identical:

const real = document.querySelector('p');
const fake = document.createElement('p');
fake.innerHTML = 'foo<br>bar';

document.body.appendChild(fake);

console.log(real.innerText); // this is not similar

console.log(fake.innerText); // to this, but why?
<p>foo<br>bar</p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading