Weber Weber - 1 month ago 5
HTML Question

Why is my javascript function to dynamically create HTML elements not working?

function addDiv(parentName, parentElement, childName, id){
var parentName = document.getElementsByTagName(parentElement);
var childName = document.createElement('div');
childName.id = id;
parentName[0].appendChild(childName);
};

addDiv(body, 'body', div, 'newdiv');


I am trying to run the above function to be able to dynamically create HTMl div's but I have been messing with it for hours and cannot figure out why it will not work. I should add I am very very new to JS. I know I could do this much easier with JQuery but I feel I should learn more about Vanilla JS first.

UPDATE 1

I'm such a noob...I just realized that Firefox's inspect tools don't show JS unless you select the tab for it. I see the errors now. I should be able to get it but will post back if I cant.

UPDATE 2
Still cant get this to work. The error I am getting is parent is undefined. But it shouldnt be because I define it below with the
var parent = document.getElementsByTagName(ptype)[i];
right?

function addElement(ptype, ctype, i){
var parent = document.getElementsByTagName(ptype)[i];
var child = document.createElement(ctype);
parent.appendChild(child);
};

addElement('body', 'div', 0);


What I do know from debugging:

-The parameters for getElementsByTagName(ptype)[i] are populating correctly, "body" and 0 respectively.

-The parent variable still shows as undefined after the script moves to creating the child variable

-Child is being populated correctly with

Got it

So I just realized. I was calling the script in the
<head>
before the
<body>
was loaded. So it was undefined because they're was no
<body>
yet. Thank you for the help @Pointy.

Answer

The getElementsByTagName() function returns a list of elements, not just one. (Note, "elements" and not "element".) Even when there's only one <body> tag, you get a NodeList back. Thus you have to pick the first element:

parentName[0].appendChild(childName);

(Also note that you need to append the node you created, and not the "id" string.)