Im trying to make an addressbook in javascript and the issue I have is that the properties of my objects are not giving me the info I need. I want 4 different property and not 4 loops of same property.
The for loop is makes a loop of 4 li
s list items thats gonna be inserted from the info I have in the objects.
But instead I got EMAIL all the loops.
Hope you understand and can help me. Here is the code.
//Contactlist funktion
function Contact(fname, lname, address, email) {
this.fname = fname;
this.lname = lname;
this.address = address;
this.email = email;
}
// Contacts
var tony = new Contact("Tony", "Stark", "Avengers 123", "i.am.ironman@hotmail.com");
var steve = new Contact("Steve", "Rogers", "Avengers 12", "cap.america@hotmail.com");
//All contacts
var contacts = [tony, steve];
// Appending the objects
var body = document.getElementsByTagName('body')[0];
var ul = document.createElement('ul');
body.appendChild(ul);
function theContacts() {
var li = document.createElement('li');
li.innerHTML = tony.fname + ' ' + stark.lname;
ul.appendChild(li);
for (i = 0; i < 4; i++) {
li = document.createElement('li');
for (var key in tony) {
li.innerHTML = key;
}
ul.appendChild(li);
}
}
// Calling the object
theContacts();
Thanks for your help!
This will output all contacts with their properties as nested unordered lists. I have given classnames to the elements for easy styling. Start just below your var contacts
.
function theContacts() {
var body = document.getElementsByTagName('body')[0],
outerUL = document.createElement('ul'),
length = contacts.length;
outerUL.className = 'contactlist';
for (var i = 0; i < length; i++) {
var cont = contacts[i],
li = document.createElement('li'),
ul = document.createElement('ul');
li.className = 'contact'; li.innerHTML = cont.fname + ' ' + cont.lname;
ul.className = 'infos';
for (var key in cont) {
var info = document.createElement('li');
info.className = key;
info.innerHTML = cont[key];
ul.appendChild(info);
}
li.appendChild(ul); outerUL.appendChild(li);
}
body.appendChild(outerUL);
}
The problem you had results from confusion with var li
inside theContacts()
.