0

Getting undefined outside of function, even though return is working fine

Hi guys, I hope someone can help me. I don't understand why I am getting 'undefined' when I log 'spellBody' outside the function. This is the reason that I am getting the error at the end. Can someone maybe help out? ``` let spellContainer = document.querySelector('.spell-container'); function createElements(element, type, parent, elementClass, elementID = '') { element = document.createElement(type); parent.appendChild(element); element.className = elementClass; element.id = elementID; console.log(element); //returns the element as HTML, gives correct output return element; } let spellBody; createElements(spellBody, 'div', spellContainer, 'spell-cast', 'some-id'); console.log(spellBody); //returns undefined let spellRes; createElements(spellRes, 'div', spellBody, 'spell-info'); //get error Cannot read property 'appendChild' of undefined ```

25th May 2020, 2:59 PM
horcrux88
horcrux88 - avatar
1 Réponse
+ 1
horcrux88 Call your function inside window.onload window.onload = function(){ createElements(spellRes, 'div', spellBody, 'spell-info' };
25th May 2020, 3:34 PM
A͢J
A͢J - avatar