document.body.innerHTML +=
breaks the reference of variablemyList
as+=
gets the HTML from the DOM and reinserted entire HTML again.
Note: Use Node.appendChild()
not .append
, The Node.appendChild()
method adds a node to the end of the list of children of a specified parent node.
A simple hack would be to redefine the variable “myList” as initially declared variable has lost the reference(Not recommended).
var myList = document.getElementById("my-list");
myList.innerHTML += "<li>3</li>"
document.body.innerHTML += "<p id='paragraph'>V School rocks!</p>";
document.getElementById("paragraph").style.textAlign = "center";
myList = document.getElementById("my-list");//this line will access the element again.
var a = document.createElement("li")
a.textContent = "element"
myList.appendChild(a)
<ul id="my-list">
<li>0</li>
<li>1</li>
<li>2</li>
</ul>
I would not recommend innerHTML +=
approach, use Element.appendChild
where you can use an earlier defined variable and it does not disturb the entire DOM tree.
var myList = document.getElementById("my-list");
var liElem = document.createElement('li');
liElem.textContent = "3";
myList.appendChild(liElem);
var pElem = document.createElement('p');
pElem.id = "paragraph";
pElem.textContent = "V School rocks!";
document.body.appendChild(pElem);
document.getElementById("paragraph").style.textAlign = "center";
var a = document.createElement("li")
a.textContent = "element"
myList.appendChild(a)
<ul id="my-list">
<li>0</li>
<li>1</li>
<li>2</li>
</ul>