6

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.

6
  • 2
    There is no object creation... we are just storing a reference to an exisitng object Commented Aug 26, 2015 at 8:04
  • You are not actually storing the element but instead creating a cacheable reference to the element at hand. Commented Aug 26, 2015 at 8:05
  • @ArunPJohny Thank you, this is all I wanted to heard. Commented Aug 26, 2015 at 8:06
  • @ArunPJohny Do you know if it works the same way with object got using jQuery? Commented Aug 26, 2015 at 8:11
  • 1
    jQuery creates a jQuery object... but the internal dom references will be the same.... so even that overhead will be very low unless you are dealing with 10s of 1000s of jQuery object Commented Aug 26, 2015 at 8:15

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

6 Comments

The object already exists in this example, so what do you mean by "The object is not created until you retrieve data.". Also why on Earth are you mentioning slowdowns on deferencing? Aside from the first sentence, this looks like a random assortment of comments that have no real meaning.
bc console.log takes forever
woops i was confusing i fixed it
What has console.log got to do with the question asked?
nothing just a good example on how retrieving data from inside something is slow
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.