Search code examples
javascriptfunctionscopedeclarationuserscripts

Declaring object out of scope


I have this function:

function createElement() {
    var element1 = document.createElement("div");
    element1.id = "el1";
    //...
}

the problem is that when I create another function, let say editElement(), I cannot access element1 from within the new function as it's out of scope.

I could declare element1 outside of those functions, but then the problem is that element1 gets declared all the time. But I may need to create the element only in the fraction of the cases, only when a user presses a button and creadeElement() gets called. I want to save system resources and call document.createElement("div") only when I really need it, but I also need to access it from within multiple functions. Is there a way to do it?


Solution

  • you can simply assign your new element to window so it available in global scope

    function createElement() {
        window.element1 = document.createElement("div"); //Meke new element global.
        element1.id = "el1";
    }
    
    function useElement() {
        //now you can use element1 directly. as it is inside the global scope.
    }