-3

I am trying to dynamically build a modal form, but when I search for my modal, then create a new child, it doesn't allow me to append them. The modal is set by class, should it be an ID instead? Please don't reference w3schools; I am using that and it's not helpful.

var a=document.getElementsByClassName('modal');
undefined
var b = document.createElement("p");
undefined
b.appendChild(a);

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
    at <anonymous>:1:3
Adam
  • 1,546
  • 2
  • 18
  • 23
Kevin Wiggins
  • 544
  • 5
  • 11

1 Answers1

3

a will be a collection of nodes (you can usually access them using [n] since they are array-like). You will want to take the first one. Try this in place of what you have:

var a=document.getElementsByClassName('modal')[0];

Typically, you use a 'class' if you have more than one. You use an 'id' if you want it to be unique. Then you can use `getElementById('xyz') and you will get a single node. In that case, no need to do the extra [0] at the end.

rasmeister
  • 1,986
  • 1
  • 13
  • 19