Pergunta

This question might seem silly, but what's the difference between accessing an element (with id "someId") using document.getElementById("someId") Vs. just typing someId ?

eg:

document.getElementById("someId").style.top = "12px";

vs

someId.style.top = "12px";

Here's a sample code http://jsfiddle.net/pRaTA/ (I found that it doesn't work in firefox)

Foi útil?

Solução

The difference is that while someId works in some browsers, document.getElementById("someId") actually complies with the W3C standard.

Outras dicas

Declaring a element DOM id doesn't mean it's available as a global variable in all browsers. The only cross compatible way to get that is to first do.

var someId = document.getElementById("someId");

Edit: I made this test code which verifies that webkit based browsers seem to make the id available as a var without first declaring it. According to this, also IE will show this behaviour.

  • Firefox: object/undefined
  • Safari: object/object
  • Chrome: object/object
  • IE: object/object (unverified)

Code:

 <html>
    <head>
    </head>
 <body>
   <div id="foo"></div>
   <script type="text/javascript">

     alert("getElementById: "+typeof document.getElementById("foo"));
     alert("as a var: "+typeof foo);

   </script>
 </body>

In client side scripting, we do document.getElementById to get the element obj in the web page. To retrieve the particular element from the DOM and its properties & methods, you need to use the getElementById method. In Jquery you can simply do var objX = $('#id')

Where as writing down id straight will not do the job. Because how will you extract the element obj from the DOM without traversing the document. document.getElementById method will pull the element information from the document. I hope this make some sense.

Using just the someId is an old way of selecting an element (i think this was implemented by IE). document.getElementById is the standard one which works on all browsers.

Considering the scenario that you only support the old IE browsers. document.getElementById is still more reliable and readable. Reliable if you are using all numbers for ids.

for example:

input element id="123"

document.getElementById('123').value; // this one works
123.value; // this one doesn't

Accessing elements as properties of the global object named after the ID of the element (your second example) is a convenience that originated in IE and has been copied by Safari and Chrome. It's a really bad idea and you shouldn't use it. The main issue is naming collisions (for example, elements with perfectly valid ids such as "alert" or "document").

document.getElementById(), on the other hand, is long-established DOM standard and, apart from some idiotic IE flaws, is foolproof. Always use it in preference to the other form.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top