run()
isn't being called until after the DOM is fully parsed, so when it attempts to execute: document.getElementById('name');
, the element will be found.
But, when that line is extracted from run()
and placed outside of the function, it is being invoked prior to the DOM being fully parsed and the element is not found.
You can solve this by placing all of your code (or the script
reference to your code), just before the closing body
tag (</body>
). By the time the browser encounters this, all of the HTML will have been parsed into memory and the element can be found.
.name { background: red; color: white; }
<!doctype html>
<html>
<head>
</head>
<body>
<div id="name" class="name" onclick="run()">Name</div>
<!-- When the script is placed after all the other body content, it will
be able to scan the DOM for any of that content. -->
<script>
var other =document.getElementById('name');
function run(){
other.classList.toggle('name');
}
</script>
</body>
</html>
And, as I mentioned in my comment, it's best not to ever name anything name
because name
is a property of the Global window
object and complications can arise when you use that identifier.