Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById("someId") Vs. someId

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)

like image 879
kwa Avatar asked Dec 01 '10 06:12

kwa


People also ask

What can be used instead of document getElementById?

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

Can you use getElementById twice?

You can call getElementById multiple times and it will work.

What is document getElementById () value?

The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.

Is getElementById good practice?

Using getElementById is the only good way to access the element, which can be done either by itself or preferably, with a function so that we can more appropriately handle errors if it can't be found. For allowing access to elements blocked by global id, this one goes to getElementById.


2 Answers

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

like image 161
Emmett Avatar answered Sep 28 '22 11:09

Emmett


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>
like image 25
Martin Algesten Avatar answered Sep 28 '22 13:09

Martin Algesten