Originally posted on my blog
TL;DR
Same as the title, don't name your global JavaScript function clear
.
TL;DR
I learned the hard way not to use clear
as the name for my global JavaScript function.
Given the example below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test 1</title>
<script>
function clear() {
document.getElementById('result').innerHTML = '';
}
</script>
</head>
<body>
<button id="clear" onclick="clear()">Clear</button>
<div id="result">Testing</div>
</body>
</html>
and clicking the Clear
button, the Testing
text will just not be removed.
I found this very cool StackOverflow explanation of why is that. The gist of it is that this way the document.clear function is being called, and simply renaming it to something like clearResult
works fine.