Possible Duplicate:
IE/Chrome: are DOM tree elements global variables here?
I am currently working on a mobile site using jquery mobile and I noticed something interesting (to me anyway, as I am still new to js). Inside a function, you can reference an element with just the id.
This is the test code I used (on chrome 22.0.x, firefox 16.0.1, and safari 5.1.7):
<!DOCTYPE html>
<html>
<head></head>
<body onload="tt()">
<div id="abc">Test</div>
<a id="cba">Test2</a>
</body>
<Script>
function tt() {
console.log(abc);
abc.style.backgroundColor = "red";
return cba;
}
</Script>
</html>
No getElementById, no jquery selector, just the id. Has it always been this way? If so, is this a good practice and why does this work? I am thinking function must have a context, but where is it, is it the page?
Any insight would be appreciated, Thanks.
getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
A commonly-used alternative to document. getElementById is using a jQuery selector which you read about more here.
IDs should be unique within a page, and all elements within a page should have an ID even though it is not necessary. You can add an ID to a new JavaScript Element or a pre-existing HTML Element.
You can call getElementById multiple times and it will work.
You are really doing:
window.abc;
This is something that IE started that was really a poor design choice.
See this great answer to a very very similar question
It's really a duplicate but the title does not reflect this.
Try this line in your console to see what I mean.
(function(){ console.log(this); })(); // logs the Window object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With