Skip to content
Advertisement

appending to the DOM – vanilla javascript

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/

function convertToJSData(arr) {
  for (var i = 0; i < arr.length; i++) {
    // var from = "10-11-2011";
    var from = arr[i].date;
    var numbers = from.match(/d+/g);
    var date = new Date(numbers[2], numbers[0] - 1, numbers[1]);
    arr[i].date = date;
  }
  console.log(arr[0].date);
  return arr;

}


function getByDate(data) {
  convertToJSData(data);
  var filterDate = new Date(2015, 09, 01);
  return data.filter(function (el) {
    return el.date >= filterDate;
  });
}


var filteredDates = getByDate(events);
filteredDates.sort(function (a, b) {
  return a.date - b.date;
});
console.log(filteredDates.length); //returns 6



var appendHTML = function (el) {
  var list = document.getElementById("events");
  for (var i = 0; i < filteredDates.length; i++) {
    var listItem = filteredDates[i].name;
    listItem.className = "event-list";
    list.appendChild(listItem);
  }
};


appendHTML(document.body);

var deleteEvent = function () {
  var listItem = this.parentNode;
  var ul = listItem.parentNode;
  //Remove the parent list item from the ul
  ul.removeChild(listItem);
}

Advertisement

Answer

when you do:

var listItem = filteredDates[i].name;
listItem.className = "event-list";
list.appendChild(listItem);

listItem is a string. You cannot append it as a child, you need to create a DOM element and append that:

var newEl = document.createElement('div');
newEl.className = "event-list";
newEl.innerHTML = filteredDates[i].name;
list.appendChild(newEl);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement