最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to insert a div after another jquery - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Feb 23, 2016 at 16:15 Zakaria Acharki 67.5k15 gold badges78 silver badges106 bronze badges asked Feb 23, 2016 at 15:57 PiccoPicco 4512 gold badges9 silver badges23 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You could use .after() function :

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

$( sopra ).after( div );
<script src="https://ajax.googleapis./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./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.

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>

发布评论

评论列表(0)

  1. 暂无评论