I am trying to determine why this script is not working -- It was working until I added the function ready element to make the page load before running - i think that maybe I did not add a correct closure. I am new to JS so if anyone has any ideas, that would be great!
    <script>
//a simple function used to make an ajax call and run a callback with the target page source as an argument when successful
function getSubPageSource(url, successCallback)
{
    var xhr = XMLHttpRequest();
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState == 4 && xhr.status == 200)
        {
            //when source returned, run callback with the response text
            successCallback(xhr.responseText);
        }
    };
    xhr.open('GET', url, true);
    xhr.send();
}
function readyFn(jQuery) {
    // Code to run when the document is ready.
//find all categories with sub categories
var categories = document.getElementsByClassName('has-subcategories');
//loop through each category
for (var ii = 0, nn = categories.length; ii < nn; ii++)
{
    //use a closure to pass in a static ii
    (function(ii)
    {
        //get element
        var element = categories.item(ii);
        //find id
        var id = element.getAttribute('data-category');
        //find url
        var href = element.getAttribute('href');
        if (id && href)
        {
            //found
            getSubPageSource(href, function(data)
            {
                //find sub categories
                //trim off everything before where id shows up first
                var substrSource = data.substr(data.indexOf('data-category="'+id+'"'));
                //trim off the remaining of the category title
                substrSource = substrSource.substr(substrSource.indexOf('</a>'));
                //trim off where the next category is found
                substrSource = substrSource.substr(0, substrSource.indexOf('home-categories-main'));
                //trim off where the next category starts, leaving source of all sub categories
                substrSource = substrSource.substring(0, substrSource.lastIndexOf('<a '))
                //insert to main menu after the title
                console.log(id, substrSource);
                //create new node capable of having children
                var newNode = document.createElement("span");
                //insert new source into the new node
                newNode.innerHTML = substrSource;
                //insert new node after element
                element.parentNode.insertBefore(newNode, element.nextSibling);
            });
        }
    })(ii);
}
}
$(document).ready(readyFn);
</script>
 
     
     
    