Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is document.getElementById('id') or $('#id') still necessary to select an element by ID?

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?

like image 977
James Lim Avatar asked Aug 30 '12 22:08

James Lim


People also ask

Which is fast document getElementById (' txtName ') or #txtName ')?

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.

What is document getElementById called?

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.

Is document getElementById () JavaScript?

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 .

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.


1 Answers

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!

like image 189
Pantelis Avatar answered Sep 21 '22 00:09

Pantelis