Picco
Picco

Reputation: 441

How to insert a div after another jquery

I have a div in html page:

<div id="home">
</div>

Now I want to put another div under the div with id=home. I mean under the other div:

<div id="home">
</div>
<div id="new">
</div>

This is my jquery code:

var div=$('div');
var sopra=$('#home');
sopra.append(div);

But this code is wrong because put the new div in the div with id=home.

Anyone can help me?

Upvotes: 2

Views: 8367

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could use .after() function :

var div=$('<div id="new">new</div>');
var sopra=$('#home');

$( sopra ).after( div );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="home">home
</div>

Or also using .insertAfter() function :

var div=$('<div id="new">new</div>');
var sopra=$('#home');

$( div ).insertAfter( sopra );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="home">home</div>

The .after() and .insertAfter() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .after(), the selector expression preceding the method is the container after which the content is inserted. With .insertAfter(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container. Hope this helps.

Upvotes: 3

Thomas Orlita
Thomas Orlita

Reputation: 1627

Pure JavaScript: You can do it using insertAdjacentHTML() method:

document.getElementById('home').insertAdjacentHTML('afterend', '<div id="new"></div>');

afterend means after closing </div> tag.


Snippet:

document.getElementById('home').insertAdjacentHTML('afterend', '<div id="new">new</div>');
<div id="home">home</div>

Upvotes: 2

Related Questions