Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to an element by id alone, no document.getElementById [duplicate]

Tags:

javascript

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.

like image 450
user1736525 Avatar asked Oct 16 '12 03:10

user1736525


People also ask

How do I grab an element by ID?

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.

What can I use instead of document getElementById?

A commonly-used alternative to document. getElementById is using a jQuery selector which you read about more here.

Can you give an element an ID in JavaScript?

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.

Can you use getElementById twice?

You can call getElementById multiple times and it will work.


1 Answers

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
like image 118
Kyle Avatar answered Sep 22 '22 16:09

Kyle