Split cookies from page

I was doing some coding today, when I got to an error:

Cannot read properties of undefined (reading 'split') 
    at getCookie ((index):38:49)
    at (index):47:31

My code (begins at line 36, ends at 43):

         var cookieArray = document.cookie.split(";");
            for (var i = 0; i < cookieArray.length; i++) {
                var cookiePair = cookieArray[1].split("=");

                if(name== cookiePair[0].trim()) {
                    return decodeURIComponent(cookiePair[1])
                }
            }

Btw, I’ve read that you can only split a string, but this is a string right?