Your example demonstrates when you have a reference to the element you want to control. If you already have a reference to the element, there is no reason to use document.getElementById
to obtain a reference to it (you already have one):
<span id="mySpan" onclick="test(this);">TEST</span>
<script type="text/javascript">
function test(el) {
// el is a reference to an element, you can use it directly
el.style.display = 'none';
// to demonstrate that the element you retrieve from gEBI
// with el.id is the same as your original reference
var elAgain = document.getElementById(el.id);
alert(elAgain === el); // "true"
}
</script>
The place where you might want to use document.getElementById
is when you want to control another element to which you don't already have a reference:
<span id="mySpan" onclick="test(this, 'myDiv');">TEST</span>
<div id="myDiv" style="display:none;">DIV REVEALED</div>
<script type="text/javascript">
function test(el, otherElId) {
// el is a reference to an element, you can use it directly
el.style.display = 'none';
// otherElId is a string containing the id of
// the element you want to control
var theDiv = document.getElementById(otherElId);
theDiv.style.display = '';
}
</script>
Note that there is rarely (if ever) a reason to do something like the following:
<span id="mySpan" onclick="test('mySpan');">TEST</span>
<script type="text/javascript">
function test(theElId) {
var el = document.getElementById(theElId);
el.style.display = 'none';
}
</script>
If the function is being fired from an element event, you can just pass this
(as per my first example), rather than passing the id of the element the event is happening on.