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>

4 Answers 4

362

try using the after() method:

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

Documentation

2
  • 10
    The .after() and .insertAfter() methods perform the same task.
    – Rifat
    Feb 11, 2010 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, 2010 at 13:25
42

try

.insertAfter()

here

$(content).insertAfter('#bla');
1
  • 22
    Shouldn't your code be more like $('<div id="space"></div>').insertAfter('#bla') rather than $('#bla').insertAfter(content);?
    – Rowan
    Feb 11, 2010 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.

3
  • Correct, but that's what happens when I try the .append() function. Feb 11, 2010 at 13:16
  • 2
    If it's XHTML then the input element should be closed (but not with an end tag). Feb 11, 2010 at 13:18
  • 2
    In HTML4 <input> should not be closed. Jun 18, 2012 at 18:43
-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>
2
  • 3
    This is incorrect. This appends the element within the parent element, just like the OP stated. Consider reading the question again and revising your answer. Feb 27, 2019 at 16:54
  • Solved 100% try using the after() method: Apr 21, 2022 at 8:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.