innerHTML Assignment Prevents the Prior Logic to Execute Properly

I am dynamically creating a “div” element and a checkbox. If my code does not contain the div.innerHTML += '<br>' line (or any other line for that matter) as below, the logic setting the checkbox to true works properly. However, if I include the said line, the checkbox is not set to true, even if the data is true. Why would having this additional line create issues?

 div = document.createElement('div')
 var checkbox = document.createElement('input')
 checkbox.type = 'checkbox'
 if (data === true) {
    checkbox.checked = true
 } else {
    checkbox.checked = false
 }
 div.appendChild(checkbox)
 div.innerHTML += '<br>' // Line creating issues
 divArea.appendChild(div)

Answer

When you assign: checkbox.checked = true you define the property (state of the checkbox check this answer).

When you use div.innerHTML it recreates (replaces) all the HTML inside div plus the one you adding. When HTML is re-created you lose checked state.

The best here is to set the attribute or add br via insertAdjacentHTML() or createElement.

//via setAttribute()
var data = true;
var divArea = document.getElementById("divArea");
var div = document.createElement('div');
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';

if (data === true) {
   checkbox.setAttribute('checked', 'checked');
}

div.appendChild(checkbox);
div.innerHTML += '<br>'; // Line creating issues
divArea.appendChild(div);
<div id="divArea"></div>

//via insertAdjacentHTML
var data = true;
var divArea = document.getElementById('divArea');
var div = document.createElement('div');
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
if (data === true) {
   checkbox.checked = true;
} else {
   checkbox.checked = false;
}
div.appendChild(checkbox);
div.insertAdjacentHTML('beforeend', '<br>'); // Line creating issues
divArea.appendChild(div);
<div id="divArea"></div>

//via creatElement
var data = true;
var divArea = document.getElementById('divArea');
var div = document.createElement('div');
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
if (data === true) {
   checkbox.checked = true;
} else {
   checkbox.checked = false;
}
div.appendChild(checkbox);
div.appendChild(document.createElement('br')); // Line creating issues
divArea.appendChild(div);
<div id="divArea"></div>

Difference between innerHTML and insertAdjacentHTML