Is referring to an element via its id considered bad?

Asked

Viewed 318 times

11

In Javascript, you can refer to any element that has a id (and in some cases a name) using simply an identifier with the same name - without the need to declare it:

<div id="teste">Teste</div>
console.log(teste); // <div id="teste">Teste</div>

Except, of course, if there is already a variable with the same name:

console.log(teste); // undefined
var teste = 10;
console.log(teste); // 10

Or if the id in question is already a property of Window (as a function built-in, for example):

<div id="alert">Teste</div>
console.log(alert); // function alert() { [native code] } 

Given these inconsistencies, I ask: is it bad to use this feature? We should only use document.getElementById instead? Or it would be a simple matter of using only "healthy" names for our element ids (i.e. not using anything that is already defined in the Javascript language)?

Li some opinions in Soen - in general saying to nay use - as well as a discussion in W3.org with arguments against and for, but I am not sure. There is some objective reason to avoid this functionality?

P.S. Although there was already pressure for this functionality to be restricted to "quirks mode", apparently it was standardized by HTML5 - so that although had past incompatibilities the future browsers should give consistent support to it.

  • 5

    It’s not an answer per se, but I think you’ve already answered the question. Using ids directly is a house of cards, at any time someone can declare a variable and break all functionality.

  • 3

    @Anthonyaccioly I agree! I thought now: it is also possible that in the future browsers will add a new property - with the same name of a id your - and with it break your code.

  • That is precisely why document.getElementById. Always use it.

  • 1

    Look more and more the worse thing instead of better, I’m reading here and it’s fun as we Web developers suffer!

  • 1

    @Harrypotter Once I read I don’t know where (in case, talking about safety) that "the web is like a car with 1000 pedals of acceleration and no brakes; the only way to stop the car is to ensure that none of the 1000 pedals is pressed..." Every time new features appear (which, I admit, are often quite cool) and with them a lot of problems. And yet the tendency [of the entities responsible for standardization] is to "ignite it" more and more. It is by these and others that I navigate with Javascript disabled (whitelisted) by default...

  • @mgibsonbr worse than that, it’s not easy no ...

Show 1 more comment

3 answers

3

You already gave the answer: the maintenance of a code like this would be unfeasible.

But there’s another point against it. According to the test below, you can see that getElementById runs about 50% faster in Firefox than using the ID name directly. In Chrome there was not so much difference. Worth testing in IE.

http://jsperf.com/console-element-using-getelementbyid-vs-nothing

That is, in addition to the "maintenance" factor, it is also worse in the "performance" factor".

  • 1

    In fact, the discrepancy was repeated in all the browsers I tested (including in IE - where this functionality was "born" and "spread" to others)

  • Humm good! Thanks for testing on the other browsers. Here I only have the FF and Chrome.

2

Window Interface -> window[name]

  • Returns a given element or a collection of elements.

As a general rule, relying on this will lead to the brittle code. Which Ids will maintain mapping for this API may vary over time as new features are added to the Web platform.

The Window interface supports named properties. Working for: the id value of any HTML element in working document. Return is generated by the user-agent (this is the part that makes it not recommended).

There has been a change to ensure compatibility with the IE:

[Gecko] [Internet Explorer] [Opera] [Webkit] 
Change how document[name] works to be compatible with both IE (which typically are targetted with <object>) and other UAs (which typically are targetted with <embed>).

Link: http://html5.org/r/6115

Due to these variations between browsers and possible updates as a given example, resource dependency is not recommended.

Source: http://www.whatwg.org/specs/web-apps/current-work/multipage/browsers.html#named-access-on-the-window-Object

1


One of the disadvantages of using dynamically created global variables via Ids is that it becomes more difficult to use a static analysis tool like Jshint to detect typos in accidentally created variable or global names. In general I prefer my variables to have lexical scope (static).

How to access the elements via window instead of by the variable name (window['teste']) is ambiguous whether you are accessing a global variable or an id of an element. I prefer to use getElementById that makes it clear what you’re doing.

And if your concern is that getElementById is a very long name, this is easy to solve:

 function byId(id){ return document.getElementById(id) }
  • After Ecmascript 5 introduced the querySelector, no longer use the getElementById

  • I still prefer to do getElementById(id) instead of querySelector('#' + id). When the string is fixed it is more a matter of taste.

  • I don’t understand, I use document.querySelector("#comments-link-22614") just as you would use $("#comments-link-22614")

  • @Ronnyamarante: This is the case with the constant ID that doesn’t matter to me.

  • "In general I prefer my variables to have a lexical (static) scope" - this, in my opinion, is the crucial point; every argument contrary to the indiscriminate use of global applies also to "treat DOM elements as if they were global". The other answers add interesting information, but I am choosing yours as the accepted answer mainly by calling attention to this point.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.