Possible Duplicate:
document.getElementById(“someId”) Vs. someId
For example I have an element with id="mybox"
attribute, is there any difference between calling it with document.getElementById('mybox')
and mybox
directly, as I see both work same in most browsers? The jsfiddle shows live example http://jsfiddle.net/usmanhalalit/TmS3k/
If there is no difference then why document.getElementById('mybox')
is so popular, is it a bad practice to call mybox
directly?
Document.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.
Definition and Usage 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.
Some browsers in some rendering modes will create a global variable for each element with an id.
It is non-standard, won't work everywhere and definitely can't be depended upon.
They don't "both work the same". IE introduced making element ids into global variables, other browsers copied it to some extent but don't fully support it. It's considered a very bad idea, just don't do it.
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