I've got an HTML form that when submitted uses PHP to dynamically build another form. The first form action uses $_SERVER['PHP_SELF'] so the second form is on the same page. The second form action is handed off and processed by a FPDF and PHP page and ultimately outputs a PDF.
JavaScript is used on the second form to dynamically build and show additional sections of the form based on input choices made on the sections of the second form as it progresses.
In my JavaScript, I have some variables I setup for ease of use that reference several areas of the second form. My JavaScript does have a window.onload function and my issue does not occur because the DOM isn't loaded before my JavaScript.
Because I dynamically build the 2nd form after the initial page load and after the first form is submitted I see this error in my Console:
TypeError: myVariable is null.
// Examples of myVariable which are HTML elements not present
// in the DOM until the first form has been submitted.
var drawingsWrapper = document.getElementById('drawingsWrapper');
var groupClass = drawingsWrapper.getElementsByClassName('group');
var groupClassLength = groupClass.length;
Once the second form is built, this error goes away as the HTML element it references is now on the page. Everything is working as expected with my forms and processing, including the JavaScript.
As I am not yet an expert on JavaScript I am making myself use it and know it very well before I start relying on a library like jQuery and I am really working hard at understanding the little nuances.
Question: Is this error acceptable given that it is thrown because the element it is referencing is not yet present in the DOM or is there something I should be doing to not declare the variable until the portion of the DOM it references it is present?