The following code按下 push
按钮时,在 Hey girls!
段落之后创建一个文本输入字段:
<html>
<head>
<script>
function func()
{
var elem=document.createElement("input");
document.body.appendChild(elem);
elem.setAttribute('type','text');
}
</script>
</head>
<body>
<p>Hey guys!<p>
<input type="button" value="push" onclick="func()"/>
<script>
func();
</script>
<p>Hey girls!<p>
</body>
</html>
如何确保在 Hey girls!
段落之前和 Hey girls!
段落之后创建文本输入字段?
最佳答案
这是 HTMLElement.prototype.insertBefore
的工作。
概要:parentElement.insertBefore(newElement,referenceElement);
示例:
document.body.insertBefore( elem, document.getElementsByTagName('p')[1] );
由于您的段落节点没有任何 ID 或 类名,我只是使用 .getElementsByTagName
引用它。如果您有更准确的查询可能性,事情就会变得更容易。
引用号:https://developer.mozilla.org/en-US/docs/DOM/Node.insertBefore
关于javascript - `document.body.appendChild(elem);` 附加到 html 正文的末尾。如何放置在 body 的特定位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12682053/