Dynamically add li to ul javascript
Try below example - use appendChild
on your UL, which you will get using getElementById()
:
var names = ["John","Mike","George"]
for (var i = 0; i < names.length; i++) {
var name = names[i];
var li = document.createElement('li');
li.innerHTML = name;
document.getElementById('friendsList').appendChild(li);
}
<ul id="friendsList"></ul>
Node.parentElement is a read only property (ie if you want to inspect the parent node of a given node)
If you want to insert nodes there are different ways:
one of the solution is to use the method appendChild on the parent node.
If you want to avoid a reflow (the browser redraws the frame) one every insertion you can first insert your elements in a document fragment
const fragment = document.createDocumentFragment();
for(let name of names){
const li = document.createElement('li');
li.textContent = name;
fragment.appendChild(li);
}
//now you add all the nodes in once
const container = document.getElementById('friendsList');
container.appendChild(fragment);
You have to append your li
to ul
. This document.createElement('li', name);
won't work.
Syntax
document.createElement(tagName[, options]);
tagName: A string that specifies the type of element to be created.
options (Optional): An optional ElementCreationOptions object containing a single property named is, whose value is the tag name for a custom element previously defined using
customElements.define()
.
document.createElement() documentation
var names = ['John', 'Jane'];
var ul = document.getElementById("friendsList");
for (var i = 0; i < names.length; i++) {
var name = names[i];
var li = document.createElement('li');
li.appendChild(document.createTextNode(name));
ul.appendChild(li);
}
<ul id="friendsList">
</ul>