See the answer by Pointy for why this happens.
To avoid the issue, there are several options. Since the problem is that a function name will classh with a property name, all revolve around unambiguously referring to the function needed.
This is the most straight forward and conflict free way to register event handlers using JavaScript.
NOTE: If the <script>
tag is in the <headd>
section or otherwise before the element that is looked up, then the JavaScript code will execute before the element is in the DOM and thus will not be found. See Why does jQuery or a DOM method such as getElementById not find the element? for more information and ways to avoid that. The two easiest ones are moving the <script>
section at the end of the body or using defer
(when the <script>
tag uses the src
attribute).
Here is a solution where the <script>
tag is moved:
<html>
<head>
<title></title>
</head>
<body>
<button>try it</button><br />
<div id="content"></div>
<script type="text/javascript">
function click() {
document.getElementById("content").innerHTML = "abc";
}
document.querySelector("button")
.addEventListener("click", () => click());
</script>
</body>
</html>
Use window.yourFunction
This will unambiguously refer to what is is defined in the global scope:
<html>
<head>
<title></title>
<script type="text/javascript">
function click() {
document.getElementById("content").innerHTML = "abc";
}
</script>
</head>
<body>
<button onclick="window.click()">try it</button><br />
<div id="content"></div>
</body>
</html>
Drawbacks
One drawback is that there can still be clashes with the same name. This time with something defined in window
.
Another drawback is that all other code can also use the global scope, the function might be accidentally overwritten.
Essentially, this solution is only one step removed from the original problem of the name of a function clashing with another name but still vulnerable to the same form of clash.
Rename the function
This will disambiguate the function by making it distinct
<html>
<head>
<title></title>
<script type="text/javascript">
function myClick() {
document.getElementById("content").innerHTML = "abc";
}
</script>
</head>
<body>
<button onclick="myClick()">try it</button><br />
<div id="content"></div>
</body>
</html>
Drawbacks
The new name can still clash with something. If not with a DOM property, then with something from window
. And if not now then perhaps later in the future when:
- a new property is added to HTML
- this could even be by somebody defining a custom attribute or custom element
- a new property is added to
window
- again, this could be another script on the page adding it
Essentially, this has a chance to merely delay the problem.