199

I have a certain textbox and I want to add a div after it. I've tried the .append() function, but that only adds the div in the element.

For example, I have:

<input type="text" id="bla" />

and I want to change that into:

<input type="text" id="bla" /><div id="space"></div>
isherwood
  • 52,576
  • 15
  • 105
  • 143
skerit
  • 19,365
  • 23
  • 96
  • 139

4 Answers4

342

try using the after() method:

$('#bla').after('<div id="space"></div>');

Documentation

T J
  • 41,966
  • 13
  • 81
  • 134
Rowan
  • 5,361
  • 2
  • 21
  • 31
  • 9
    The .after() and .insertAfter() methods perform the same task. – Rifat Feb 11 '10 at 13:21
  • 8
    That's correct, but it depends on the way you prefer to code it. I'd normally have the '#bla' input selected already, and then add the extra content afterwards. Purely my preference though, I'm not sure whether either method has a speed benefit. – Rowan Feb 11 '10 at 13:25
43

try

.insertAfter()

here

$(content).insertAfter('#bla');
Rifat
  • 7,470
  • 4
  • 30
  • 45
  • 19
    Shouldn't your code be more like `$('
    ').insertAfter('#bla')` rather than `$('#bla').insertAfter(content);`?
    – Rowan Feb 11 '10 at 13:27
7

First of all, input element shouldn't have a closing tag (from http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT : End tag: forbidden ).

Second thing, you need the after(), not append() function.

naivists
  • 31,708
  • 5
  • 57
  • 81
-3

Solved jQuery: Add element after another element

<script>
$( "p" ).after( "<strong>Hello</strong>" );
</script>

OR

<script type="text/javascript"> 
jQuery(document).ready(function(){
jQuery ( ".sidebar_cart" ) .insertAfter( "<a href='http://#'>Continue Shopping</a>" );
});
</script>
Ashar Zafar
  • 378
  • 2
  • 11