Why is my JavaScript variable returning null?

I’m having trouble with a piece of JavaScript code. It’s supposed to show a hidden div when a file is selected, but it’s not working. Here’s what I’ve got:

function toggleElement() {
    let hiddenBox = document.getElementById('hidden-element');
    hiddenBox.style.display = 'block';
}

let fileInput = document.getElementById('file-selector');
fileInput.onchange = toggleElement;

And here’s the HTML:

<input type="file" name="file-upload" id="file-selector">
<div id="hidden-element" style="display: none;">
    <button onclick="addMoreFiles()">Add another file</button>
</div>

When I try to run this, I get an error saying ‘fileInput is null’ on the line where I set the onchange event. I’ve checked for typos and made sure the script is linked correctly in the head section. What am I missing here? Any help would be appreciated!

hey mia92, sounds like a timing issue. ur script might be running before the dom’s fully loaded. try wrapping ur code in a DOMContentLoaded event listener:

document.addEventListener('DOMContentLoaded', function() {
    let fileInput = document.getElementById('file-selector');
    fileInput.onchange = toggleElement;
});

this should fix it. lmk if u need more help!

I ran into this exact problem a while back. The issue is likely that your JavaScript is executing before the DOM is fully loaded, so it can’t find the element you’re trying to manipulate. Here’s a quick fix that worked for me:

Instead of using onchange, try addEventListener after the DOM is loaded. Like this:

document.addEventListener('DOMContentLoaded', function() {
    let fileInput = document.getElementById('file-selector');
    fileInput.addEventListener('change', toggleElement);
});

This ensures your code runs only after all the HTML elements are available. Also, make sure your script is either at the bottom of your HTML file or uses the ‘defer’ attribute if it’s in the head.

If this doesn’t solve it, check if you have multiple elements with the same ID. That can cause unexpected behavior. Hope this helps!

I encountered a similar issue recently. The problem likely stems from script execution order. To resolve this, consider moving your script tag to the end of the body element instead of the head. This ensures all DOM elements are loaded before your JavaScript runs. Alternatively, you could use the ‘defer’ attribute on your script tag in the head:

<script src="your-script.js" defer></script>

This tells the browser to delay script execution until the document has finished loading. Either method should resolve the ‘null’ error you’re experiencing. If these solutions don’t work, double-check that your file input’s ID matches exactly in both HTML and JavaScript.