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>

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

Leave a Reply