Actually live and learn!

window.onload = function() { div_1.onclick = function() { div_2.value = div_1.innerHTML; } } 
 <div id="div_1">TEXT</div> <input type="text" id="div_2" value="" /> 

It works in all browsers that are only on the computer!

Q: Why declare a type variable as

 var mydiv = document.getElementById("mydiv"); 

and then refer to it if the appeal can be made immediately to mydiv ? Explain!

UPD: @ling waiting for your personal visit! Your knowledge has been tested by your own js code more than once)

  • one
    @butteff, he's talking about: div_2.value - Oleg Arkhipov
  • five
    Actually waiting for the guru ) - Palmervan
  • one
    @Palmervan, you often lag behind life =) From birth, I didn’t know anything like that and didn’t even think) + to the question)) - Vitaly Kustov
  • 3
    I recently discovered that for myself var obj = {}; var n = function () {return false; } var obj2 = {a: 15} obj [n] = 3; obj [obj2] = 5; In my opinion, this is scary)) - Sh4dow
  • one
    @ling you would also read my answer about this - Zowie

5 answers 5

For a start - a little theory. This is IMHO stupidity, at one time, started IE, this was not supported by other browsers, after - it became supported by chrome, at the same time - this kind of behavior is approved by the html5 standard (yes, and there is something through F, well, not the essence ). Accordingly, support is really at the level of support (except for the paradox that it will not work in old non- IE), moreover, support will remain and it will not go anywhere, so I don’t quite understand what is right in the answer @ Alex Silaev ?

Well, now let's get to the practical part, such elements are stored in the global scope, respectively, for example, a situation may arise, such as:

 <!-- наш HTML --> <div id="hello">классно работает!11!</div> <!-- один из наших скриптов --> var hello = function(){ /* function code... */ } <!-- другой наш скрипт --> hello.onclick = function(){ alert(this.innerHTML); } 

What happens in this case, I think it is clear Naturally, someone may argue, they say - if you do everything neatly, then everything will be ok and I do not deny it, often it will be so. But, to put it mildly - not always. The more code you have - the higher the probability of catching an unpleasant bug will become. Of course, if you understand that global variables are evil, etc. etc. - you will correctly structure your code, but in this case you will also choose the elements, humanely. Otherwise, you have a hard binding to the html structure, even worse than with document.getElementById ('someId'). Actually - all this looks like magic, respectively, looking through the code, trite, it is not clear - where did this hello come from, for example, it becomes obvious when the amount of code becomes, at least 300+ lines. Suppose I need to change this id, I change it in DOM, I search by the scripts where it is used, but I still don’t find it. (you can be sure) - I’ll look for exactly $ in the case of jq, prototype and getElementById in the case of "pure" JS, now I’m not writing in the context of myself, but in the context of the person who will look at the code you wrote, your partner or who replaces you at work. And, in fact, this is normal, not everyone knows this, and even in books where it is mentioned - they write briefly, they say, look at it this way you can do it, describe how it works and then it is possible , but not necessary In all books, something like this is written further - accordingly, in our book we will not do that. Of course, I understand that everything is not always written correctly in books (this is especially true with books on javascript), but the fact that not all books are written about this and that, for example, you haven’t I knew this, in my opinion, already says that no one needs it. offtopic - and confirms the saying "you know less - sleep better" =)

I would also like to add, to the above, the inconvenience in terms of pairing with the coder or, in this case, much worse - with another JS developer.

In general, briefly summarizing - to put it mildly - I do not recommend (not just me) in the absolute majority of cases, the reasons (without inventing something complicated, but in real life, believe me - the problems will be more interesting) are described above. What do we win? Yes, actually, we gain practically nothing ...

One more “type” argument can be that it is faster — perhaps it is so, but getElementById works so quickly (and absolutely everywhere) that it is not serious to be guided by this. But even if you want, do something like this:

 function getElementById(id) { return window[id] !== undefined && window[id].id === id ? window[id] : document.getElementById(id); } 

Actually, such an approach solves the problem of "erasing", but, at the same time, it does not relieve the brevity of the record. On the other hand, this function will work normally everywhere and in the DOM; if the element is saved in the window, it will not work. Once again I draw your attention - this is saving on matches.

I parry a piece of UPD by @ Anton Mukhin about the id of the form "div-id" - you can easily and easily get them by calling window ["div-id"], the browser does not calculate anything.

I will try to sum up very brief results - just don’t use it, know that you can understand how this or that javascript code works, no more (IMHO)

PS: 2 @northerner nobody says that they are fools there, they want to do better. Regarding javascript without getElementById - if the question explicitly asks, “how is getElementById better or so?”, What is the relation to the question that you wrote about? Either I misunderstand something, or you did not carefully read the question.

UPD: Time has already shown everything, if it were needed, it would have been used in wide circles a long time ago, because nothing like that is observed - nobody needs it (or rather, someone needs to adopt such standards once, but to whom - I have no idea). I will once again emphasize that we are talking about browser javascript, perhaps somewhere, this is convenient and is practiced by the majority, then of course - use your health (thanks to cap).

  • And I like this behavior. Using id as an object in Javascript code seems to be a very natural reference to elements. I, of course, write in JavaScript not for the Web, but for the implementation of the logic of the QML interfaces, there is an id addressing there and no problems. Conducting an analogy, I suspect that the convenience of access by id will manifest itself when implementing the interactive on the HTML5 canvas. As for the example, I think that its shortcoming is not in the address by id, but in the appeal to the function globally. When using namespaces, the situation described is not possible. Are there any other examples of problems - northerner
  • @northerner - your suspicions are not grounded, in general, where does html canvas come from? .. I am very fond of this technology and, I dare to assure you, the code for working with DOM ~ = 0, respectively, really didn’t understand what you were talking about. The examples I have given are true for both html and any other tree structure. Actually, there is no huge, “unkillable” lack of this behavior, but there is no tangible benefit either. Accordingly, it is better to do as everyone does. Of course, if you write something yourself from and to - write as you like, it is absolutely violet here, I wrote in the context of the norms of scale and command - Zowie
  • And I do not like this behavior because in JS everything is built around the global area, but no, everything is small, you give more -_- - Zowie
  • And in general - the functionality is doubtful, not everyone needs it to put it mildly and, to put it mildly, not always, moreover - it can be implemented without any problems. Accordingly, I do not understand at all who approved this (censore). - Zowie
  • This is the answer I was waiting for! @AlexWindHope Thank you! - Palmervan

Discussion on StackOverflow and more .

This is the behavior of IE, which was later copied by other browsers, and mentioned in the HTML5 standard. see 5.2.4 Named access on the Window object .

The bottom line is that in this case the reference goes to the property of the window object. In other words, browsers make it possible to access elements with the specified id through the window object, which is the global context, so window ['id'] can be omitted, id is enough, well, except for invalid id from the point of view of the variable name (yes, minuses and so on.) ...

Nobody really likes this kind of practice, and if it’s not to remove this behavior from the standard, then to make it available at least for quirks mode, and not to touch standard mode.

Consider making the global scope of pollution by names / ids quirks-only

  • @Yura Ivanov is a good answer, and most importantly, roomy and clear! Thank. On the stack I saw from the part in the question like mine was [here] [1] [1]: hashcode.ru/questions/74756/simple- questions -to -js- scripters - Palmervan

The answer is simply the correct approach. No one guarantees that such a method will "live" or will be supported further. And getElementById will be.

This is about the same as the road to the red light to go. After all, it is possible, but no one guarantees that after this nothing will happen to you. (Although in Russia can occur on the green). But this is not the point, but the fact that the approaches are different and the probability of an accident, too. Moreover, if suddenly there is no support for this thing, then you will have to look through all the code and change everything. And if there is no getElementById support, then I will simply redeclare it and I will have it :)

And the actual answer to the question is that you will rather lose your life if you use it :)

  • The bottom line is that I was not going to give up the standard application ... Going through the methods of the approach and stuff, I found out that it all works, so it became interesting about the existence of pitfalls ... - Palmervan
  • yes to the article, if this method works in IE6 and the most ancient Firefox not to mention the opera, the probability that this method will be rejected is similar to that of getElementById. But I repeat that I do not dare to dispute! - Palmervan
  • See the dock;) - Alex Silaev
  • the exact link plz) - Palmervan
  • I incidentally have a friend, a non-potent js'er, I'll write to him again! I’ve been hard-nosed) thanks to obstinacy I have achievements!) - Palmervan

And you try to give the item

 <div id="div-1">TEXT</div> 

What do you think that will try to make the browser when performing div-1 ?
Right! It will try to subtract 1 from the variable div ! How, then, to do without expression

 var mydiv = document.getElementById("div-1"); 

???
UPD1
You can still add! There are elements created at runtime. Well, they, therefore, ID are given dynamically. It would be foolish for such cases not to dynamically set variables like this:

 my_dynamic_id.onclick = function() { //Бла-бла-бла } 

Better, probably, like this:

 // начало какого-нибудь цикла обработки //.... //получаем ID из какой-нить функции, предоставляющей id элементов var my_id_i = document.getElementById(getNextDynamicId()); my_id_i.onclick = function() { //Бла-бла-бла } 

Then how does this situation turn out when you can directly access the element my_div directly? Just when creating this DIV element, the global variable my_div . But it will be overwritten if you declare a globally variable with the same name as the element ID :

 <script type="text/javascript"> var my_div = 'АГА!!!!'; function aga() { alert(my_div); alert(document.getElementById(my_div)); } </script> 

Here, in the first case, "АГА!!!!" , in the second, something like "HTMLDivElement" .
So it turns out that your application may, by mistake or oversight, break down due to the inadvertent declaration of a variable with the same name as the ID of your element.
So what happened? The browser first declared the global variable my_div, which we successfully rewrote!
Somehow like this. Even my case cited here can be considered a “pitfall”.

  • one
    @ Anton Mukhin You so answered as if I were promoting this approach ... I collect information on the subject of the approach and not the ditch of the gut that I invented something super mega necessary for every web site! From the word of the wise man - who wishes can remove the letter p - Palmervan
  • Here, I brought one more of the pitfalls ... :) - Anton Mukhin
  • 2
    And now, in your >> Question: Why declare a type variable as var mydiv = document.getElementById ("mydiv"); and then refer to it if the appeal can be made immediately to mydiv? Explain! also clarified some situation, why. - Anton Mukhin
  • one
    I support this answer. I do not think that addressing by id directly is a dirty hack, an undocumented feature will be cut out :) I am writing in QML, which is also scripted by JavaScript - there using id elements as JavaScript objects is the main recommended practice. But as shown in the examples, getElementById () is universal and can be used if the id is not directly addressed due to the syntax or if the name id is set to a variable. - northerner

I will answer in response to my question in a dispute of answers and comments from the respondents ...

The bottom line: I always use native js as part of my projects, which only I do.

@Alex Silaev is probably your best answer yet, but part of your answer is:

if there is no getElementById support, then I will simply redeclare it and I will have it

I will write a smart php script that transforms all the necessary entries in the right places and formats the js script for all the mega innovations so as not to poke around in the kilometer js code! At the moment I see no reason not to use the method that I cited in the example! I will again come across in the framework of my project!

@ Anton Mukhin I will open for you an interesting function:

 function $(id) { return document.getElementById(id); } 

and then you can use the line from my example in the question as

 $("div_1").onclick = function() //... 

Now I’ll say that within my project I know that I need to use underscores and not hyphens, this is the first.

Secondly, I rarely use such tinsel and mostly in css klsasy! What concerns the program code and ID names as follows: var nodeName or id="idName" have been trying for a long time to exclude tinsel and unnecessary signs!

  • You do not know all the knowledge, you do not take into account all the subtleties, you cannot change all the methods! In some cases, - some tricks are useful, in other cases - others. It all depends on the specific task! Here, @northerner enlightened that, it turns out, in some cases, the example you cited is even recommended! But looking at your statement that you are trying to eliminate tinsel and unnecessary signs ... I think that this should not be misused because, I think, can worsen the readability of the code. - Anton Mukhin
  • @ Anton Mukhin - you really won't know everything, but you need to strive for it. This undoubtedly not only can, but also worsens the readability of the code - Zowie