最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

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

Share Improve this question edited Feb 1, 2015 at 16:40 Deduplicator 45.8k7 gold badges72 silver badges123 bronze badges asked Jan 15, 2013 at 12:32 Govind BalajiGovind Balaji 6417 silver badges17 bronze badges 4
  • 2 The function .addElement does not exist in the DOM afaik. – Felix Kling Commented Jan 15, 2013 at 12:33
  • 1 I remend to read w3/wiki/Creating_and_modifying_HTML. This might also help: w3/wiki/Traversing_the_DOM. – Felix Kling Commented Jan 15, 2013 at 12:35
  • @FelixKling Sorry createElement – Govind Balaji Commented Jan 15, 2013 at 12:35
  • or look at this dustindiaz./add-remove-elements-reprise – Rachel Gallen Commented Jan 15, 2013 at 12:39
Add a ment  | 

2 Answers 2

Reset to default 3

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

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论