Forum Moderators: open

Message Too Old, No Replies

Assigning document object to variable

Not just the specific object name; the whole thing

         

frobozz

4:43 pm on Aug 3, 2010 (gmt 0)

10+ Year Member



All my code is working, I'm just trying to keep the script trim and lean.

This is working fine:

document.getElementById('sample').style.display = "block";


But my attempt to clean it up is not working:

var hello = document.getElementById('sample').style.display;
hello = "block";


The whole "document" string appears several times in the code, so it's redundant. Which is why I want to just assign it to a variable.

I've tried adding "value" to the end, like this:

var hello = document.getElementById('sample').style.display.value;


But that doesn't work either, as I expected. After all the whole object is a value. It's got something to do with my using an explicit name in getElementById. If I trim it down like this, it works:

var hello = document;
hello.getElementById('sample').style.display = "block";


But that's hardly worth anything, doesn't do much to keep the code clean. Any ideas?

Fotiman

5:16 pm on Aug 3, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In JavaScript, primitive types like strings, numbers, and booleans are passed by value. Objects, functions, and arrays, however, are passed by reference.

So you could store a reference to the DOM node object by doing:


var o = document.getElementById('sample');
o.style.display = "block";
o.style.display = "none";


The style property of a DOM node is also an object, so you could do:



var o = document.getElementById('sample'),
s = o.style;
s.display = "block";
s.display = "none";


The display property of style, however, is a primitive string. So if you do this:


var o = document.getElementById('sample'),
s = o.style,
d = s.display; // d gets a copy of the current value
d = "block"; // does not affect o's style


You are just storing a copy of the string value.

Hope that helps.

frobozz

6:05 pm on Aug 3, 2010 (gmt 0)

10+ Year Member



Thank you Fotiman, this does help. Understanding how JS recognizes these items via object, reference, etc. is the key -- and Googling for help without having the right terms is futile. :)

In this case, declaring a second new variable to make it all come together is probably on par with the code's current efficiency, so I'll just call it even. But now I know!

Fotiman

7:01 pm on Aug 3, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Also, just to clarify, in my example I created multiple variables o and s, but that was simply for demonstration purposes. If you didn't need a reference to the DOM object itself, you could omit o:


var s = document.getElementById('sample').style;
s.display = "block";


Just wanted to make sure that was clear. :)