Why use getElementById

I have a question about code such as is in JavaScript DOM HTML. For example:

var element = document.getElementById("header");
element.innerHTML = "New Header";

I do not understand why getElementById is used like that. Why not just use the element’s id directly? The following will do the same thing:

header.innerHTML = "New Header";

I assume there are situations where getElementById is necessary. My guess is that people are just in the habit of using getElementById whether it is necessary or not. There are many other situations where people use syntax that is not necessary, such as using braces in if statements (in JavaScript, Java, C#, C++ and others derived from C) even when they are not necessary so that is my best guess for this situation too. If it is, then can someone provide an example of when getElementById is necessary?

1 Like

lol, for your example I would do

var element = document.getElementById("header");
element.textContent = "New Header";

Partly I guess. But I think being consistent and readability play a large part. eg.

I could do

if(1===1) do_something();

but I would write it as

if ( 1 === 1 ) {
  do_something();
}

To me, even though not necessary, I feel the “cost” is minimal compared to the benefit.

Only in some browsers and only if the code is in the global namespace.

To have it work in ALL browsers and have it work inside functions you must use getElementById

felgall, can you be more specific about when it would not work to use the id directly?

Actually, It increases readability of the code.
When I see only

header.innerHTML = "New Header";

I may wonder what does header exactly mean.
Is it a DOM element or some other object with the same property (innerHTML)?
Is it a plain DOM element object or it was modified (extended) somewhere before that point?
Using getElementById is a clear way to say “it’s just a plain DOM element”.
Of course, that only matters if you care about other coders who may want to work with your code.

It’s a good practice to use braces for if statements, even when there is only one line of code inside the if.
Imagine a situation when you had such if statement without braces and some time later you decided to add another line to it. It’s so easy to forget to add braces after that (because they’re required now). And, although code is still correct for the compiler, it will work in unexpected way. That is a quite common situation.

I apologize for saying anything about braces and if statements. I should know that explanations such as that is likely to cause off-topic discussion.

As for all the explanations about why to use getElementById, I think books and articles about DOM programming using JavaScript should provide explanations such as is here. I might not agree but the explanations should be provided instead of simply saying do it that way. Authors should be clear and specific on the subject.

In general, we may rephrase that question about getElementById to “Why global variables are bad?”.
I think many of coding books answer that question.

[quote=“SamuelCalifornia, post:1, topic:219022, full:true”]can someone provide an example of when getElementById is necessary?
[/quote]

When no element with the id exists, attempting to access it directly will give you an error. Using document.getElementByid will instead give you null, which can be more appropriately handled.

Other issues are that elements with a name attribute can also be access directly. Using document.getElementById gives better surety that the correct element will be accessed.

And of course, it provides better clarity to people reading your code about what is happening there.

In addition there is the js root level name space.

say for example you have a document with a tag with the ID=‘myEl’. but your document also loads a .js, perhaps one developed later or independently, in that script you have a line: var myEl =50; So…what is the value you should expect for myEl, now? (it’s 50 ,btw, but you really don’t want that kind of ambiguity)I could do

if(1===1) do_something();
but I would write it as

if ( 1 === 1 ) {
do_something();
}
To me, even though not necessary, I feel the “cost” is minimal compared to the benefit.

those two are similar but not the same tho. the brackets ALLOW for multiple command to be applied in the case of a condition

consider:

if(1===1) do_something();
do_somethingELSE();

vs

if ( 1 === 1 ) {
  do_something();
  do_somethingELSE();

}

Attempting to access the element directly, gives in the following example, an uncaught reference error:

<p>Giz me da kodes: <input name="test"></p>
<script>
test.onchange = function () {
    alert('I can haz ' + this.value + '!!');
};
</script>

With getElementById we have the choice of programming a bit more defensively:

<p>Giz me da kodes: <input name="test"></p>
<script>
var test = document.getElementById('test');
if (test !== null) {
    test.onchange = function () {
        alert('I can haz ' + this.value + '!!');
    };
}
</script>

which doesn’t result in an error, and won’t do anything until the input has an attribute of id=“test”

Why is the ability to program more defensively useful? Sometimes we are adding our script to a page that we have no control over, so being able to handle different types of situations can be quite vital.

I prefer to think of that in a slightly different way. Without the braces, a developer might add another line of code to the condition, failing to realise that only the first one will be conditional:

if ( 1 === 1 )
  do_something(); // is conditional
  do_somethingELSE(); // always runs, is not conditional

Commence much pulling of hair as they try to figure out where they went wrong.

Having the braces always there results in better clarity, and prevents those problems from occurring in the first place.

if ( 1 === 1 ) {
  do_something(); // is conditional
  do_somethingELSE(); // is also conditional
}

It’s not so much that the cost is minimal. The greater aspect is that it results in greater code clarity, and easily prevents larger problems from occurring later on down the road.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.