38

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

How do I do that?

joews
  • 29,767
  • 10
  • 79
  • 91
DiegoP.
  • 45,177
  • 34
  • 89
  • 107
  • 3
    Please post an example, i.e. the HTML you have and the HTML you want to get. Where is the `click` handler bound to? – Felix Kling May 30 '11 at 08:33

3 Answers3

131

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 newElement is the element to be inserted and someElement is the element it is to be inserted after.

W3C insertBefore method of the Node interface

RobG
  • 142,382
  • 31
  • 172
  • 209
  • note that `nextSibling` may not work in IE – Zameer Ansari Jul 25 '16 at 15:31
  • 3
    @student–[*nextSibling*](https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#attribute-nextSibling) was introduced in DOM level 1 (1998) and works back to IE 5 at least. – RobG Jul 26 '16 at 00:07
14

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.

Correct answer from @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

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>

Ibu
  • 42,752
  • 13
  • 76
  • 103
8

outerHTML method does the trick too:

allAloneElement.outerHTML+='<p>I am the new element</p>'
user3711851
  • 105
  • 1
  • 3