1

I am trying to add an input field to a created element. This is my code.

var Images_to_beuploaded_cont = document.getElementById("Images_to_beuploaded_cont");

  var carCont = document.createElement('div');
  carCont.className += "multipleImageAdding";

  Images_to_beuploaded_cont.insertBefore(carCont, Images_to_beuploaded_cont.firstChild);

So, the code above adds the following

<div id="multipleImageAdding"></div>

What I want to do is the code below.

<div id="multipleImageAdding">
   <input type="text" name="fname">
</div>

Is this even possible? to add an element to another after it was created?

1
  • Of course, yes. Just appendChild your input to div. Commented Feb 22, 2017 at 3:50

1 Answer 1

1

Is this even possible? to add an element to another after it was created?

Yes, you could add the input element before or after appending the parent container element.

After creating the input element and adding the desired type and name attributes, just use the appendChild() method:

var input = document.createElement('input');
input.type = 'text';
input.name = 'fname';

carCont.appendChild(input);

Snippet:

var Images_to_beuploaded_cont = document.getElementById("Images_to_beuploaded_cont");

var carCont = document.createElement('div');
carCont.className += "multipleImageAdding";

var input = document.createElement('input');
input.type = 'text';
input.name = 'fname';

carCont.appendChild(input);

Images_to_beuploaded_cont.insertBefore(carCont, Images_to_beuploaded_cont.firstChild);
<div id="Images_to_beuploaded_cont"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

this worked like a charm. Now, all I will have to figure out is how to add it at the bottom of the div if I even add another element inside that div. Thanks mate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.