Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html element id as javascript variable

Consider the following code:

<html>
<head></head>
<body>
<div id='test' class='blah'>
  <a href='http://somesite.com/' id='someLink'>click!</a>
</div>
</body>
</html>

So I just recently discovered that this creates a javascript object called someLink and I can for instance get the value of the href attribute with someLink.href. I tested this in the latest Chrome, FF and IE and it works.

First off, how long has this "feature" been around? I imagine probably a while, because I have known for years that IDs for html elements on a page must be unique, and if you do have more than one element sharing the same ID, the last one overwrites the previous one(s), and using for instance getElementById() will return the last one. But I never really understood why, but now, looking at it as a "this is creating an object" perspective, it makes sense. So, as far as being able to directly access it with the id-name-as-javascript object...how long has that been around? IE6 era? Earlier?

2nd...I guess this is more of a discussion point than question, but... IMO this doesn't seem like a very good "feature" to have... Isn't the whole point of having a DOM and wrapper functions like getElementById(), to give some organization and more importantly, cut down on namespace issues? I don't feel I should have to be worried about random html elements on a page overwriting my javascript variables (something that has recently happened, which is why I discovered this "feature"). Does anybody know why this is as it is, what's the logic behind it?

like image 547
slinkhi Avatar asked Mar 16 '12 15:03

slinkhi


People also ask

Can id be variable in JavaScript?

An identifier is a sequence of characters in the code that identifies a variable, function, or property. In JavaScript, identifiers are case-sensitive and can contain Unicode letters, $ , _ , and digits (0-9), but may not start with a digit.

Can any HTML element have an id?

In HTML5, the id attribute can be used on any HTML element (it will validate on any HTML element.

How do you set the id of an element in HTML?

The value of the id attribute must be unique within the HTML document. The id attribute is used to point to a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specific id. The syntax for id is: write a hash character (#), followed by an id name.


1 Answers

First off, how long has this "feature" been around?

It is a Microsoft-ism that cropped up around IE 4 if I remember correctly.

Some other browsers have added support for it in an effort to be compatible with badly written code that depends on it. Some may only support it in quirks mode.

this doesn't seem like a very good "feature" to have

Correct. Don't use it. :)

like image 77
Quentin Avatar answered Sep 22 '22 07:09

Quentin