Search code examples
javascripthtmlcssfrontendappendchild

appendChild is not responding after class change - VANILLA Javascript


I found answers alluding to this question but most of them seemed to be based on jQuery. As an exercise I am building a image slider app in jQuery and then Javascript. I want to understand what jQuery is doing under the hood, and be able to make the decision to use it or not based on the project.

My problem is this: when I click the next button, I want the gallery to slide to the left, and prevImg will be removed, currentImg will become next and so forth. I will then add a li element with the appropriate class nextImg and the image.

Everything is working fine, but the line of code nextImg.appendChild(next_ImgPath) is not appending an image.

function slideAnimSetting(direction) {
    counterAction();

    if (direction == 1) {
        establishImgPaths();

        for (var i = 0; i < innerListEl.length; i++) {
            leftPosition = innerListEl[i].offsetLeft;   
            topPosition = innerListEl[i].offsetTop;
            Tween.to(innerListEl[i], 1, {left: leftPosition-700});
        };  // end for  

        prevImg.removeAttribute('class');
        currentImg.className = 'prevImg';
        nextImg.className = 'currentImg';

        listEle = document.createElement('li');
        listEle.className = 'nextImg';

        for (var i = 0; i < innerUlEl.length; i++) {
            innerUlEl[i].appendChild(listEle);
        }; //end for

        nextImg = document.getElementsByClassName('next-img');
        nextImg = nextImg[0];
        nextImg.appendChild(next_ImgPath);

        setImageStyles();
    }
}; // end slideAnimSetting

The console.log is telling me that nextImg is undefined.


Solution

  • You gave it a className of nextImg, but you're searching for next-img.