I have no clue as to why console.log(li.length);
returns 0
when console.log(document.getElementsByClassName("list-group-item"));
returns an array. console.log("AFTER");
gets printed after the array, so it looks like it completed skips the 2nd for loop but I define the li elements beforehand.
var categories = ["business", "entertainment", "gaming", "general", "music", "science-and-nature", "sport", "technology"];
function makeUL(array) {
var overview = document.createElement('div');
overview.setAttribute("class", "well");
overview.setAttribute("style", "max-height: 300px;overflow: auto;");
var list = document.createElement('ul');
list.setAttribute("id", "check-list-box");
list.setAttribute("class", "list-group checked-list-box");
overview.appendChild(list);
// Create the list element
for(var i = 0; i < array.length; i++) {
// Create the list item
var item = document.createElement('li');
item.setAttribute("class", "list-group-item");
item.setAttribute("id", "checkedData");
// Set its contents
item.appendChild(document.createTextNode(array[i]));
// Add it to the list
list.appendChild(item);
}//end for loop
var checkedItems = [], counter = 0;
console.log(document.getElementsByClassName("list-group-item"));
var li = document.getElementsByClassName("list-group-item");
console.log(li.length);
//loop through li elements in categories to add listeners
for(var i = 0 ; i < li.length; i++){
console.log("INSIDE");
li[i].addEventListener('click', function(event) {
event.preventDefault();
//disallow repeats
if(checkedItems.indexOf(li[i].innerText) == -1){
checkedItems[counter] = li[i].innerText;
counter++;
console.log("added");
}
//remove element if unchecked from array
if($('checkedData').is(':checked') == false){
var index = checkedItems.indexOf(li[i].innerText);
console.log(li[i].innerText +": " + index);
checkedItems.splice(index, 1);
console.log("disabled");
counter--;
}
});
}
console.log("AFTER");
// Finally, return the constructed list
return list;
}
document.getElementById('cat').appendChild(makeUL(categories));