Govind Balaji
Govind Balaji

Reputation: 639

How to add an element in a HTML document using pure javascript at particular position of the document

I know I can add an element using javascript by:
document.createElement('input');
But I want to add it in a particular position of the document, like after the submit button, or after the textfield

Upvotes: 3

Views: 4889

Answers (2)

ATOzTOA
ATOzTOA

Reputation: 35950

Try this out:

s is the element you want to put the new element after.

var s = document.getElementsByTagName("input")[0];
var newNode = document.createElement("input");

s.parentNode.insertBefore(newNode, s.nextSibling);

This will place the new input after the current input.

Alternatively:

var f = document.getElementsByTagName("form")[0];
var newNode = document.createElement("input");
f.appendChild(newNode);

Upvotes: 3

SBI
SBI

Reputation: 2322

You can get a node with one of the GetElementsBy functions, and then append new DOM Elements with Node.appendChild().

Upvotes: 1

Related Questions