Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between document.getElementById('mybox') and mybox? [duplicate]

Tags:

javascript

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?

like image 565
Muhammad Usman Avatar asked Sep 20 '11 14:09

Muhammad Usman


People also ask

What does document getElementById() do?

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.

When we use document getElementById in JavaScript?

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.


2 Answers

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.

like image 72
Quentin Avatar answered Sep 30 '22 19:09

Quentin


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.

like image 42
RobG Avatar answered Sep 30 '22 18:09

RobG