문제

Below is some sample code.

<body>
    <div id="wrapper" class="access">
        <form id="test">
            <input id="password"></input>
            <input type="submit"></input>
        </form>  
    </div>
    <script>
        console.log(password);
        alert(wrapper.className);
    </script>
</body>

The console log returns the DOM element with id password. The alert is "alert".

It works in normal code as well, e.g. var x = wrapper.className;

Surely this is not right? What is the point of document.getElementById, $('#password') or goog.dom.getElement if it just works like this? Are these functions just for legacy now?

It works in Firefox, Chrome and Safari, incidentally.

도움이 되었습니까?

해결책

This answer should give you a lot to go on:

https://stackoverflow.com/a/6381766/944006

You shouldn't use these variables, and you DEFINITELY don't want to depend on them working correctly across browsers.

다른 팁

Backwards compatibility is the reason IDs are mapped to properties of the window.

It's also a major reason to avoid global variables - in fact some browsers will outright break if you try to use a global variable that's the same name as an element's ID.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top