1

I have this javascript function:

function clearDiv(div_id) {
    alert(div_id);
    $(div_id).empty();
}

And the following html:

<input value="Clear" type="button" onClick="clearDiv(div_to_clear)" />

<div id="div_to_clear">
    <!-- more html -->
</div>

Why is it that the above will actually find the javascript div object with id div_to_clear and use the $ selector to access it?

If I had done the input as :

<input value="Clear" type="button" onClick="clearDiv('div_to_clear')" />

I would need to change my function to

function clearDiv(div_id) {
    alert(div_id);
    $('#' + div_id).empty();
}

Is there any documentation about this? Are there advantages to using one method or the other?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

3 Answers3

5

IE (and Chrome in an effort for compatability) will create properties on the window with names of elements with ids, corresponding to those elements.

In the first example are are passing window.div_to_clear which points to your element directly. In the second, you are passing a string telling jQuery which element to select.

The first one is non-standard behavior so you should not rely on it.

Dennis
  • 32,200
  • 11
  • 64
  • 79
  • Because I don't have firefox installed right now, will the first method pass `div_to_clear` as a string to my js function? – Sotirios Delimanolis Feb 20 '13 at 21:22
  • @SotiriosDelimanolis No. An unquoted string is treated like a variable, as previously noted in this answer. – Daedalus Feb 20 '13 at 21:26
  • I actually just tried it in Firefox and it works, which is new to me. Still, I wouldn't rely on it. And if it is not quoted, it is not a string. – Dennis Feb 20 '13 at 21:27
1

The first one is actually a browser bug (they called it a feature) to access the DOM node by window.div_to_clear (the global variable) - and jQuery creates its wrapper around the element. For legacy reasons, it still exists in current browsers, but is deprecated. Your really should use the selector solution.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

This is because there is a widely-implemented (although not best practice) method by browsers to automatically place html elements with id's into their correlating variable name. For example:

<div id="someId"></div>

will end up psuedo creating the variable someId which holds that html element.

These questions have similar information on the behavior:

Do DOM tree elements with ids become global variables?

Where does the variable holding an element with an id get stored?

Element accessible with ID

Here is a jsperformance test showing that accessing the id in that manner is slower than using document.getElementById: http://jsperf.com/global-id-vs-document-getelementbyid

Community
  • 1
  • 1
Travis J
  • 81,153
  • 41
  • 202
  • 273