简体   繁体   English

如何在文档的特定位置使用纯JavaScript添加HTML文档中的元素

[英]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: 我知道我可以使用javascript添加一个元素:
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 但我想将它添加到文档的特定位置,例如在submit按钮之后,或在textfield

Try this out: 试试这个:

s is the element you want to put the new element after. s是您想要将新元素放在后面的元素。

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 . 这将会把新的input电流后input

Alternatively: 或者:

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

您可以使用其中一个GetElementsBy函数获取一个节点,然后使用Node.appendChild()附加新的DOM元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM