I came across this gist today, and in the comments the author mentioned that
var log = document.getElementById('log');
is unnecessary, because in Javascript you can just use log
to access the DOM element. Is this true across all browsers? Is there a name/reference for this technique?
The simple answer is document. getElementByID('txtName') is faster than $('#txtName') because jQuery is written on top of javascript. It means internally jQuery is using only native javascript codes.
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.
Introduction to JavaScript getElementById() methodThe document. getElementById() method returns an Element object that represents an HTML element with an id that matches a specified string. If the document has no element with the specified id, the document. getElementById() returns null .
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.
Surprisingly this is actually in the HTML5 spec, so yes it will work and no it is not a legacy feature as it is being suggested (anymore at least - it used to be an IE only trick).
You can read the spec here, http://www.whatwg.org/specs/web-apps/current-work/#named-access-on-the-window-object
I will agree that it's actually clutters the namespace, and would take the liberty to suggest against using it - but it will and does work on every major browser!
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