I have a function that is meant to clear a div of all its children with a specific name before refilling said div with a new set of children.
function displaySearchResults(resultsList) {
var length = resultsList.length;
var searchDiv = document.getElementById('search-results');
//CLEAR DIV
if(searchDiv.hasChildNodes()) {
for(var i=0; i<searchDiv.childNodes.length; i++) {
var oldChild = searchDiv.childNodes[i];
if(oldChild.id.indexOf('search-results-row') != -1) {
searchDiv.removeChild(oldChild);
console.log('Removed Result!');
}
}
}
//ADD CHILDREN
for(var i=0; i<length; i++) {
console.log('Added Result!');
var element = resultsList[i];
var rowDiv = document.createElement('div');
rowDiv.id = 'search-results-row' + i;
rowDiv.className = 'list listRow' + i%2;
rowDiv.setAttribute('onclick', 'mapCurrentContact(' + i + ');');
rowDiv.innerHTML = element.firstName + ' ' + element.lastName;
searchDiv.appendChild(rowDiv);
}
}
However it starts running the ADD CHILDREN portion of the function before the CLEAR DIV loop has a chance to finish. So for instance, if the function finds 4 childNodes in the div and begins looping through to remove each one with the id of search-results-row, it will only get through 2 or so before it begins appending the new set of results that was initially passed into the function.
I know that Javascript runs asynchronously, but I thought that functions themselves at least run top down so the bottom portion should not do anything until we reach that part of the code? I have tried all sorts of other alternatives such as running the CLEAR DIV portion in its own function and then calling the ADD CHILDREN portion at the end, but I always get the same results. What am I missing here!?!
When you remove items from the beginning of a list:
You end up skipping over element
band repeating the same error for every other element in the list. You can either decrement the counter when you remove something or simply start from the end of the list, in which case you will only affect the index of elements you have already looked at. The latter is more widely accepted.