Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are HTML DOM elements stored by reference in Javascript array?

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.

like image 637
Delgan Avatar asked Sep 27 '22 22:09

Delgan


1 Answers

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.

like image 78
kemicofa ghost Avatar answered Oct 20 '22 13:10

kemicofa ghost