1

In sample code of the yui library, I see this notation:

var obj = document.getElementById("coffee_msg"); obj.style.display = 'block'; 

As obj is only used once, I would rather prefer this:

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

Is there any reason why the first notation is used in the yui library and many other places? Are there incompatibilities with certain browsers?

4 Answers 4

2

If you only need to set one property it doesn't matter at all (as long as you do not want to check if the return value is valid before trying to access a property of it).

However, if you have multiple properties you'll want to do the lookup only once (even though an id lookup is extremely fast), so assigning the element to a variable is the way to go in that case.

Of course you could make this even shorter with jQuery: $('#coffee_msg').show()
Also has the advantage that you do not get an error if the element does not exist for some reason. And if you want to set multiple CSS properties etc, you can simply use a function that does that for you with a single call or chain multiple calls to different jQuery methods.

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

3 Comments

Note that there isn't jQuery tag on this question.
That's why the answer is not jQuery-only. There is no rule stating that you cannot mention jQuery in a question not tagged with jQuery.
:) I thought you didn't notice. I've nothing against jQuery you know... :)
2

The two different ways work exactly the same. Using a temporary obj variable could be useful to improve readability of the code (but it should be given a name better than obj in that case).

Comments

2

There isn't a "real" reason, just to make the code a little bit more readable.

Just like with:

var myAge = 26; var myAgeNextYear = myAge + 1; 

VS:

var myAgeNextYear = 26 + 1; 

My personal preference is to keep a reference to the obj only if I'm using it more than once.

Comments

0

The first option is useful because it improves readability, it also makes the obj variable available immediately for other use. I would use this example personally.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.