Javascript 如何使用javascript一个接一个地编写一个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6173941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:33:37  来源:igfitidea点击:

How to write an element just after another with javascript?

javascriptelement

提问by DiegoP.

I need to append an element onclick just after another (a textarea).

我需要在另一个元素(一个文本区域)之后附加一个 onclick 元素。

How do I do that?

我怎么做?

采纳答案by Ibu

Update: This question may not answer the question properly but it was selected as the right answer. So I am adding the correct answer here since most people don't scroll past it and the original author hasn't accessed Stackoverflow for many years now.

更新:此问题可能无法正确回答问题,但已被选为正确答案。所以我在这里添加正确的答案,因为大多数人不会滚动过去,而且原作者已经很多年没有访问过 Stackoverflow。

Correct answer from @RobG

来自@RobG 的正确答案

var div = document.getElementById( 'div' );
var newText = document.createElement( 'textarea' ); // create new textarea
div.parentNode.insertBefore( newText, div.nextSibling );

Old Irrelevant answer:

旧的无关答案:

You can use the appendChild method to add a new element

您可以使用 appendChild 方法添加新元素

HTML

<div id='div'>
  <textarea></textarea>
</div>

Javascript

var div = document.getElementById('div');

var newText = document.createElement('textarea'); // create new textarea

div.appendChild(newText); // add it to the div

Resulting HTML

<div id='div'>
  <textarea></textarea>
  <textarea></textarea>
</div>

HTML

<div id='div'>
  <textarea></textarea>
</div>

Javascript

var div = document.getElementById('div');

var newText = document.createElement('textarea'); // create new textarea

div.appendChild(newText); // add it to the div

结果 HTML

<div id='div'>
  <textarea></textarea>
  <textarea></textarea>
</div>

回答by RobG

The accepted answer will work in this specific case, but to insert an element after another more generally, the following does the job:

接受的答案将在这种特定情况下起作用,但要更一般地一个接一个地插入一个元素,以下工作:

someElement.parentNode.insertBefore(newElement, someElement.nextSibling);

Where newElementis the element to be inserted and someElementis the element it is to be inserted after.

其中newElement是要插入的元素,someElement是要插入的元素。

W3C insertBeforemethod of the Node interface

Node接口的W3C insertBefore方法

回答by user3711851

outerHTMLmethod does the trick too:

outerHTML方法也可以解决问题:

allAloneElement.outerHTML+='<p>I am the new element</p>'