Why Don't We Just Use Element Ids as Identifiers in JavaScript

Why don't we just use element IDs as identifiers in JavaScript?

Anyway, this method seems to be quite poorly documented, and In fact, the sources I come across don't even give it a mention [...]

Reliance on implicitly-declared global variables aside, the lack of documentation is a great reason not to use it.

The apparent promotion of id values into global variables isn't standards compliant (the HTML5 spec for the ID attribute doesn't mention it) and, therefore, you shouldn't assume future browsers will implement it.

EDIT: It turns out this behaviour is standards compliant - In HTML5, window should support property access to "Named Elements":

Named objects with the name name, for the purposes of the above algorithm, are those that are either:

  • child browsing contexts of the active document whose name is name,
  • a, applet, area, embed, form, frameset, img, or object elements that have
    a name content attribute whose value is name, or
  • HTML elements that have an id content attribute whose value is name.

Source: HTML 5 spec, 'Named access on window object", emphasis mine.

Based on this, standards compliance is not a reason to avoid this pattern. However, the spec itself advises against its use:

As a general rule, relying on this will lead to brittle code. Which
IDs end up mapping to this API can vary over time, as new features are
added to the Web platform, for example. Instead of this, use
document.getElementById() or document.querySelector().

Javascript: Why get an element with getElementById(id) when it is still present in js?

why is this so?

Because early browsers did that, and it's now become standardized.

why do we have to even use getElementById(id) instead of simply writing id?

Technically, you don't. But beware that the global namespace is really, really crowded. There's a whole bunch of stuff thrown in there. Not just elements with IDs, but certain elements if they have names, the browser context by name, etc., etc., which means there can be conflicts. For instance, if you had an element with id="document", the automatic global won't be created. The other, conflicting globals can vary by browser. Also, id values that aren't valid JavaScript identifiers (like id="foo-bar") are still perfectly valid id values, but the automatic global for it (window["foo-bar"]) is awkward to use.

Using getElementById specifically looks for an element with that ID1 (not name, etc.). So it's more contained and reliable.


1 Ignoring bugs in obsolete versions of IE, which failed to constrain it correctly.

HTML: Can always the same identifier be used for name and id attributes?

Is there any reason to choose different identifiers for the name and id attributes?

Yes. IDs must be unique, names don't have to be. Names must be the same for members of a radio group, so they can't all have the same id—well, they can in practice but accessing the elements by ID will be problematic. And if you don't access them by ID, why have it?

Are there any use-cases for which different identifiers are required?

Yes, radio buttons. Only one can have an id that is the same as its name. But otherwise, there are few restrictions, such as than never give form controls the name or id of a method or property of the form itself, like "submit", as it will mask the same–named property of the form.

Also, names "_charset_" and "isindex" are special.

Are there any differences in syntax? (for example you can use "myarray[123]" for the name attribute and PHP will understand that correctly and create an array, can that also be used in a similar manner for id-attributes in Javascript or CSS - and if not, is that a syntax-error or is it simply a valid identifier with brackets in it?)

Yes. The rules for name and id attribute values are similar but an ID must not contain spaces (and some values for name are special, see above). There were more restrictions on id attributes in HTML4 (e.g. ids couldn't start with a number), but in practice they weren't implemented in browsers.

Some characters that are valid in names and ids must be quoted to use as CSS selectors, e.g. for:

<div id="d[]">

the CSS selector is:

#d\[\]

and for use with the Selectors API:

#d\\[\\]

(e.g. document.querySelector('#d\\[\\]').

Are both case-sensitive?

Yes.

What is the point of getElementById when JS finds elements by name anyway

Elements with an id become Global properties of the window object in the Browser's Object Model (BOM). It is not "JavaScript" that makes this happen. Accessing an element with getElementById() uses the Document Object Model (DOM) API, which is standardized. The BOM is largely not standardized. Using the DOM is the best practice.

Unique element ID, even if element doesn't have one

UPDATE: Closures are indeed the answer. So after fiddling with it some more, I figured out why closures were initially problematic and how to fix it. The tricky thing with a closure is you have to be careful when iterating through the elements not to end up with all of your closures referencing the same element. For example, this doesn't work:

for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var button = document.createElement("button");
button.addEventListener("click", function(ev) {
// do something with element here
}, false)
}

But this does:

var buildListener = function(element) {
return function(ev) {
// do something with event here
};
};

for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var button = document.createElement("button");
button.addEventListener("click", buildListener(element), false)
}

Anyway, I decided not to select one answer because the question had two answers: 1) No, there are no internal IDs you can use; 2) you should use closures for this. So I simply upvoted the first people to say whether there were internal IDs or who recommended generating IDs, plus anyone who mentioned closures. Thanks for the help!

Why does PHP only parse DOM elements using 'name' identifiers, and not 'id'?

Why does PHP not use id tags?

That's not PHP, that's HTML. PHP has nothing to do with the HTML spec.

HTML does use id attributes, but it uses them for a different purpose than name attributes.

HTML form elements build requests (POST or GET generally) from their child value-carrying elements (input, select, textarea, etc.). The name attribute is used as the key, and the value (or selected value, etc.) is used as the value.

This creates the key/value pairs for the data in the request.

There seems to be a lot of waste in having to duplicate the same string for both the id and name of an element within a form

You don't have to duplicate it. You may personally choose to duplicate it. But that's your choice. There's no rule in any specs/standards/conventions/etc. indicating that you must or even should do that.



<input id="foo" />            <!-- JS/CSS accept this -->
<!--- incorrect. JS/CSS can also target name attributes if necessary. -->

<input name="foo" /> <!-- Only PHP accepts this -->
<!--- incorrect. This isn't PHP, this is HTML. PHP isn't involved here at all. -->

<input id="foo" name="foo" /> <!-- Everyone's happy -->
<!--- if that's the markup you choose to define, sure. -->


Related Topics



Leave a reply



Submit