Storing references to HTML elements in JS, what's the convention?

Viewed 81

In my app.js file I do a lot of document.getElementById('some-element') calls. I think it would be more readable and maintainable to store the result of this call to a variable and then access the element through it whenever I need to. What's the common way to do this in vanilla JS so that they're available in all functions? Do I need to create global variables?

1 Answers

Just set it to a variable at the top level of your code

const someElement = document.getElementById('some-element');

function firstFunction () {
    // access by using 'someElement'
}

function secondFunction () {
    // access by using 'someElement'
}
Related