Nick
Nick

Reputation: 6025

Javascript: GetElementById - when does the DOM hit hit?

I'm doing this:

var hpl = doc.getElementById("hpl");

and then this:

hpl.style.height = 28 + "px";

My question: am I accessing the DOM twice, once to reference the element, and then a second time to set the style height?

If so, then am I right in concluding that this is inefficient with respect to DOM calls, even though it minimises nicely.

var hpl = document.getElementById("hpl");
if (test === "Abel") {
    hpl.style.height = 28 + "px";
} else {
    hpl.style.height = 42 + "px";
}

So this would be better in terms of speed:

if (test === "Abel") {
    document.getElementById("hpl").style.height = 28 + "px";
} else {
    document.getElementById("hpl").style.height = 42 + "px";
}

I've got a jsperf here which suggests there is no real difference, although I'd like to understand the theory behind this. Thanks.

Upvotes: 0

Views: 121

Answers (2)

jfriend00
jfriend00

Reputation: 707326

The two different ways you're doing it are no different from the standpoint of accessing the DOM.

var hpl = doc.getElementById("hpl");
hpl.style.height = 28 + "px";

This finds the DOM element that has the id="hpl", puts it into a local variable and then uses the local variable to directly reference the DOM element (no searching required) to modify it.


When you do it this way:

document.getElementById("hpl").style.height = 28 + "px";

the only difference is that you don't store it in a local variable (though it is stored internally in the javascript engine). It still gets the DOM element by finding the DOM element that has id="hpl" and then uses that reference to the DOM element to directly set the style value. No significant difference between this and the first way.

A stored reference to a DOM element is a very efficient way to access a DOM element. No searching is required. Internally in the browser/javascript engine, the DOM reference is a data structure that contains a fast way to get to the actual DOM object (probably a pointer to it, but the actual implementation is up to the browser).

Upvotes: 1

OneMore
OneMore

Reputation: 1179

As far as I know, once you've accessed the DOM element by Id once, it's put into a dictionary for quick reference later (like a hashtable/hasmap).

Upvotes: 2

Related Questions