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?