var elemText = document.getElementById("insert");
for (var k = 1; k <= 4; k++) {
for (var j = 1; j <= k; j++) {
elemText.innerHTML += ('*');
};
elemText.innerHTML += ('<br>');
};
Teardown:
document.getElementById("insert").innerHTML = "";
Is there a coding error? Is is just horribly inefficient (I think this unlikely to be the sole reason)? Is it something to do with the way the test is set up?
Yes. You forgot to reinitialize the
<div>in test #2. You need to empty it, just as you setresult = []in test #1. Doing it in the teardown is not enough, and test #2 will generate much longer texts before clearing than test #1.Also, your test cases have not the same result. Since you want to output
<br />elements in test #1 as well, you would need to useinnerHTMLthere, too. Your current code did output<br>literally as text.Improved test setup
Yes. Working with
innerHTMLis inefficient – it needs the HTML parser each time you assign to it, and you are doing it very often. Also, since you are using+=it needs to serialize the DOM each time.