Weber Weber - 1 year ago 62
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'); = id;

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.


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.

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];

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

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
before the
was loaded. So it was undefined because they're was no
yet. Thank you for the help @Pointy.

Answer Source

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:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download