简体   繁体   中英

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.

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 .

Javascript just saves it as a reference.

The object is not dereferenced until you retrieve data.

Like console.log([reference to dereference and log])

There is no slow down until the data is dereferenced

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM