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)
A commonly-used alternative to document. getElementById is using a jQuery selector which you read about more here.
You can call getElementById multiple times and it will work.
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.
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.
The difference is that while someId
works in some browsers, document.getElementById("someId")
actually complies with the W3C standard.
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.
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>
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