I have a custom JavaScript object and I want it to be "linked" with an element from the DOM.
var my_object = {}
var element = document.getElementsByClassName("a_class")[7];
my_object["element"] = element;
As I will need many of these objects, I wondered if directly storing DOM object obtained from .getElement()
was a good idea?
I am scared that this will construct heavy objects. Is it the case, or does Javascript use some kind of clever and light references?
Alternatively, I thought to add a custom id
to the element before stroring this id
but this is less convenient.
Yes, if you store an HTML DOM element into an object, you are storing its reference.
This is good practice because imagine if you have to access an element multiple times, rather than finding that element
every single time, get it once and store it.
The process of finding an element
is a lot less efficient compared to retrieving it through an object
, especially if you use jQuery
.
It does not take up a lot of memory, but this doesn't mean you should be storing every single HTML element
on your page in an object
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With