document.getElementByID(id) returns a node that doesn't exist [closed]

1 day ago 3
ARTICLE AD BOX

I have a function that selects an iframe using document.getElementById(id) and changes its source based on another parameter. I'm encountering a strange behaviour with this function when it is called using the onsubmit attribute of an HTML <form> tag, the element that is being found by getElementById doesn't actually exist. It exists in the HTML document, and when I console log it the element that it thinks is selected is the correct HTML tag, but the arrow to reveal the properties dropdown cannot be clicked and when I go to highlight the node in the DOM inspector nothing is highlighted. Additionally, the src attribute of the real iframe is reset to how it appears in the HTML before any scripts have been executed. When I call the same function, using the same parameters, from the console, the node is selected properly and its src attribute is set to the new parameter, but for whatever reason when the function is called using onsubmit it behaves differently.

Function:

const pages = { test1: "value1", test2: "value2", test3: "value3" }; function promptSubmit (input, dict, frame) { const iframe = document.getElementById(frame); console.log(iframe); const elem = document.getElementById(input); const selector = elem.value; if (selector in dict) { const source = `./pages/prompts/${dict[selector]}.html`; console.log(`Current src: ${iframe.src} Intended new src ${source}`); iframe.src = source; console.log(` Source changed, current source: ${iframe.src}`) } else { console.log("Command unrecognised"); }; };

HTML:

<body> <main> <form onsubmit="promptSubmit('input', pages, 'content');"> <input type="text" id="input"> </form> </main> <iframe id="content" src="./pages/temp.html"></iframe> </body>

Any ideas why this might be happening and how I might fix it?

HTML with script tag (MRE)

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="charset" content="UTF-8"/> <script> const pages = { test1: "value1", test2: "value2", test3: "value3" }; function promptSubmit (input, dict, frame) { const iframe = document.getElementById(frame); console.log(iframe); const elem = document.getElementById(input); const selector = elem.value; if (selector in dict) { const source = `./pages/prompts/${dict[selector]}.html`; console.log(`Current src: ${iframe.src} Intended new src ${source}`); iframe.src = source; console.log(` Source changed, current source: ${iframe.src}`) } else { console.log("Command unrecognised"); }; }; </script> </head> <body> <main> <form onsubmit="promptSubmit('input', pages, 'content');"> <input type="text" id="input"> </form> </main> <iframe id="content" src="./pages/temp.html"></iframe> </body> </html>
Read Entire Article