Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  30] [ 4]  / answers: 1 / hits: 41819  / 7 Years ago, sat, december 23, 2017, 12:00:00

I have an array of names and I want to show them on my page.
I created an empty ul in my html



<ul id=friendsList>
</ul>


And now I want to add the names to this ol but I doesn't work



for (var i = 0; i < names.length; i++) {
var name = names[i];
var li = document.createElement('li', name);
li.parentElement('friendsList');
}


Error:
Exception was thrown by user callback. TypeError: li.parentElement is not a function


More From » html-lists

 Answers
74

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>




[#55606] Tuesday, December 19, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;