2

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.