210

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
  • 58,414
  • 16
  • 114
  • 157
Jelle De Loecker
  • 20,999
  • 27
  • 100
  • 142

4 Answers4

362

try using the after() method:

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

Documentation

T J
  • 42,762
  • 13
  • 83
  • 138
Rowan
  • 5,597
  • 2
  • 22
  • 32
  • 10
    The .after() and .insertAfter() methods perform the same task. – Rifat Feb 11 '10 at 13:21
  • 9
    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
42

try

.insertAfter()

here

$(content).insertAfter('#bla');
Rifat
  • 7,628
  • 4
  • 32
  • 46
  • 22
    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
  • 32,681
  • 5
  • 61
  • 85
-5

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
  • 382
  • 2
  • 11