I wanted to practice my vanilla javascript skills since I’ve been so library-heavy lately. My goal was to filter an array of JSON data (by events after 10/01/2015), and then append them as list items to the DOM, with the class being “events”, and give the ability to delete events. Why isn’t this working?
https://jsfiddle.net/youngfreezy/7jLswj9b/
JavaScript
x
50
50
1
function convertToJSData(arr) {
2
for (var i = 0; i < arr.length; i++) {
3
// var from = "10-11-2011";
4
var from = arr[i].date;
5
var numbers = from.match(/d+/g);
6
var date = new Date(numbers[2], numbers[0] - 1, numbers[1]);
7
arr[i].date = date;
8
}
9
console.log(arr[0].date);
10
return arr;
11
12
}
13
14
15
function getByDate(data) {
16
convertToJSData(data);
17
var filterDate = new Date(2015, 09, 01);
18
return data.filter(function (el) {
19
return el.date >= filterDate;
20
});
21
}
22
23
24
var filteredDates = getByDate(events);
25
filteredDates.sort(function (a, b) {
26
return a.date - b.date;
27
});
28
console.log(filteredDates.length); //returns 6
29
30
31
32
var appendHTML = function (el) {
33
var list = document.getElementById("events");
34
for (var i = 0; i < filteredDates.length; i++) {
35
var listItem = filteredDates[i].name;
36
listItem.className = "event-list";
37
list.appendChild(listItem);
38
}
39
};
40
41
42
appendHTML(document.body);
43
44
var deleteEvent = function () {
45
var listItem = this.parentNode;
46
var ul = listItem.parentNode;
47
//Remove the parent list item from the ul
48
ul.removeChild(listItem);
49
}
50
Advertisement
Answer
when you do:
JavaScript
1
4
1
var listItem = filteredDates[i].name;
2
listItem.className = "event-list";
3
list.appendChild(listItem);
4
listItem
is a string. You cannot append it as a child, you need to create a DOM element and append that:
JavaScript
1
5
1
var newEl = document.createElement('div');
2
newEl.className = "event-list";
3
newEl.innerHTML = filteredDates[i].name;
4
list.appendChild(newEl);
5