Reputation: 1175
I have the following code in which I attempt to iteratively create label element newDay
(to which I append newDayIcon
and finally append to newWeekSet
:
...
console.log(dict);
var newLine = document.createElement('div').classList.add('list-group-item');
var newButton = document.createElement('div').classList.add('add-button');
var newTemp = document.createElement('a');
var newName = document.createElement('a').classList.add('name-font');
var newWeekSet = document.createElement('div').classList.add('right-align');
Object.entries(dict).forEach(function([key, value]) {
console.log(key, value);
var newDay = document.createElement('label').classList.add('day-font');
var newDayIcon;
console.log(newDay);
newDay.textContent = key.charAt(0);
if (value) {
newDayIcon = document.createElement('i').classList.add('far', 'fa-check-circle', 'fa-xs')
newDayIcon.style.color = 'Blue';
}
else {
newDayIcon = document.createElement('i').classList.add('far', 'fa-times-circle', 'fa-xs')
newDayIcon.style.color = 'Orange';
}
newDay.appendChild(newDayIcon);
newWeekSet.appendChild(newDay);
});
var newMoveIcon = document.createElement('i').classList.add('fas', 'fa-bars');
newButton.id = 'schedule-'+i++;
newLine.append(newButton, newName, newWeekSet, newMoveIcon);
dashboard.appendChild(newLine);
}
with the following current output:
Friday: null,
Monday: Object {
EndTime: "12:50 A.M.",
StartTime: "12:55 A.M."
},
Saturday: null,
Sunday: Object {
EndTime: "12:50 A.M.",
StartTime: "12:55 A.M."
},
Thursday: null,
Tuesday: null,
Wednesday: null
}
"Sunday" Object {
EndTime: "12:55 A.M.",
StartTime: "12:59 A.M."
}
undefined
TypeError: undefined is not an object (evaluating 'newDay.textContent = key.charAt(0)')
I can't seem to figure out why newDay
element can not be created in this way - is there a particular reason this won't work?
Upvotes: 0
Views: 192
Reputation: 820
I think I see the issue. document.createElement('label').classList.add('day-font');
doesn't return a value. Anywhere you use the result of classList.add
you're essentially assigning the var to undefined
.
I see this pattern in many places in your script. I suggest creating the element and assigning the value to a var before you try to manipulate it like so:
var newDay = document.createElement('label');
newDay.classList.add('day-font');
// do even more things to newDay if you want.
Anywhere where you create a new element and then try to update that element later, you'll want to split the steps apart like that.
Let me know if you have any questions!
Upvotes: 2