How can I add an element after another element?
Asked Answered
H

4

215

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>
Haerle answered 11/2, 2010 at 13:12 Comment(0)
D
365

try using the after() method:

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

Documentation

Dude answered 11/2, 2010 at 13:18 Comment(2)
The .after() and .insertAfter() methods perform the same task.Headrail
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.Dude
H
43

try

.insertAfter()

here

$(content).insertAfter('#bla');
Headrail answered 11/2, 2010 at 13:17 Comment(1)
Shouldn't your code be more like $('<div id="space"></div>').insertAfter('#bla') rather than $('#bla').insertAfter(content);?Dude
U
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.

Undressed answered 11/2, 2010 at 13:15 Comment(3)
Correct, but that's what happens when I try the .append() function.Haerle
If it's XHTML then the input element should be closed (but not with an end tag).Cherianne
In HTML4 <input> should not be closed.Valve
D
-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>
Dative answered 16/1, 2018 at 13:25 Comment(2)
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.Nodarse
Solved 100% try using the after() method:Dative

© 2022 - 2024 — McMap. All rights reserved.