I am using the following function to set up DOM elements using Javascript:
createDomEl(type, parentEl, id) {
let el = document.createElement(type);
parentEl.appendChild(el);
el.id = id;
return el;
}
It works just fine, unless I try to append a DOM element to document.body. I have tried passing in the body element several ways, including:
const body_el = document.body;
or
const body_el = document.getElementsByTagName('body')[0];
and
createDomEl('section', body_el, 'main-section');
But I get the TypeError: parentEl.appendChild is not a function
.
EDIT: I've moved the script tag to be inside the body, like so:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<script src="build/bundle.js"></script>
</body>
</html>
I can log the body element before calling this function, i.e.
console.log(body_el)
This logs:
<body>...</body>
I can also directly substitute document.body
for parentEl
in the function, and the function works. The issue seems to be passing it in.
The createDomEl
function is in a class imported into a main class from which it is called as a method of an instance, like so:
import CreateDomEls from './helpers/createDomEls.js';
class Layout {
constructor(config) {
this.createDomEls = new CreateDomEls();
this.createMainSection();
}
createMainSection() {
const body_el = document.getElementsByTagName('body')[0];
console.log(body_el);
const mainSection = this.createDomEls.createDomEl(
'section',
body_el,
'main-survival-game-station'
);
}