I'm new to importing modules in ES6. I have a simple module with a function for creating and appending an HTML element.
I am able to call and pass arguments to the function, however, I cannot read any properties from the DOM. I am receiving errors such as this:
Uncaught TypeError: Cannot read properties of null (reading 'parentNode')
I have simplified my code below:
main.js
import * as watm_fn from "./modules/functions.js";
document.addEventListener("DOMContentLoaded", function (event) {
watm_fn.createToggle("#container");
}
functions.js
export function createToggle(elm) {
const toggleElementID = document.getElementById(elm);
const languageToggle = document.createElement("select");
toggleElementID.parentNode.replaceChild(languageToggle, toggleElementID);
}
I get a similar error when trying to return the innerHTML of toggleElementID
Is accessing and manipulating the DOM via an imported module possible? And if so, what am I doing wrong?
(I am not using node or jquery in this project)
Well I feel dumb. I'm used to coding in jQuery where you include the "#" in front of your IDs, but I forgot that getElementById does not require that. Removing that from my passed argument resolved the issue.
Uncaught TypeError: Cannot read properties of null (reading 'parentNode')
This error suggests that the below line is failing toggleElementID is null:
toggleElementID.parentNode.replaceChild(languageToggle, elm);
Look at the code searching for the element
const toggleElementID = document.getElementById(elm);
As per getElementById An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document.
So there is no matching element found with the supplied elm id.