Is storing DOM elements in objects a bad idea?

let DOM = {
    body   : document.body,
    button : document.getElementsByTagName("button")[0],
    parent : document.querySelector(".parent"),
    // ...
}

Are there any drawbacks if you do this?
Especially when you have a lot of DOM elements?

Not really, because you’re not saving those DOM elements. You’re creating a reference to them. The thing in the html page and the thing in the variable or array or object? Same thing. only one of them.

The memory space taken would bee negligible, and on the plus side, you have a quick way to refer to them in your script.

Go with it!

1 Like

I would say no. You aren’t really storing the DOM object in there, you are storing the memory address that points to it. Doing what you did takes up no more memory than:

const body = document.body;
const button = document.getElementsByTagName("button")[0];
const parent = document.querySelector(".parent");

You’re just wrapping it an object for convenience.

2 Likes

thanks for quick the reply

Thanks for the reply :blush:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.