Javascript Function Events Not Firing in Order
<p>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. </p>

<pre><code>function displaySearchResults(resultsList) {
var length = resultsList.length;
var searchDiv = document.getElementById('search-results');

//CLEAR DIV
if(searchDiv.hasChildNodes()) {
    for(var i=0; i&lt;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&lt;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);
}
}
</code></pre>

<p>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.</p>

<p>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!?!</p>
