4

I've encountered a funny thing recently when I try to access the DOM element by id. So, let me show you what I got.

Here is the HTML code:

<!DOCTYPE HTML>
<html>
<head></head>
<body>
    <ul id='here' data-hi='123'>
        <li id='li1'>1</li>
        <li id='li2'>2</li>
        <li id='li3'>3</li>
    </ul>
</body>
</html>

I try to access the second list item with the id "li2" and remove it, here is the JavaScript code:

var ul = document.getElementById('here');
ul.removeChild(li2);

Obviousely, the "li1" is not defined before it's been used. However, this code works, the seconde item in the list was removed.

than, I try another code like this:

here.removeChild(li2);

It's still working!!! I try to run this code on Chrome44, Firefox40 and IE11, the code worked fine on these browser.

Then I tried to give the second li tag a name called "li2name", and did the same thing:

<li id='li2' name='li2name'>2</li>

here.removeChild(li2name);

An error was throwed:

Uncaught ReferenceError: li2name is not defined

My question is why it works when I try to access the element directly with a object name after the ID of the element? Dose the JavaScript engine invoke the document.getElementById implicitly for us?

Ziran Wu
  • 41
  • 3
  • 1
    It's by design. ID's are mapped right into the `window` object for backward compatibility. It's one of the old dark sides of JS :) – Roko C. Buljan Aug 23 '15 at 08:57
  • `name` on a LI (DIV, etc) element is invalid. So, I hope you have your answer. For more info on the `name` attr: https://developer.mozilla.org/en-US/docs/Web/API/Element/name – Roko C. Buljan Aug 23 '15 at 09:06
  • Thank you all guys, I found my answer according to the [Do DOM tree elements with ids become global variables?](http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables). I looked into the window object, and found the some property with the name "here" "li2", and `console.log("here" in window)` did output `true`. Thank you all for helping me get the answer. – Ziran Wu Aug 23 '15 at 09:16

0 Answers0