简体   繁体   English

如何使用jQuery将div添加为倒数第二个div?

[英]How to add a div as the 2nd to last div with jQuery?

I know that .append puts the code at the end, and .prepend puts it in the front, but I have 5 divs within a parent div, and I want some html code to be added dynamically right before the last child div. 我知道.append将代码放在末尾,而.prepend将其放在前面,但是我在父div内有5个div,我希望在最后一个子div之前动态添加一些html代码。 How can I do that? 我怎样才能做到这一点?

$('#parent > div:last-child').before('<span>something</span>');

jsFiddle . jsFiddle

You can flip the whole thing around too. 您也可以翻转整个过程。

$('<span>something</span>').insertBefore('#parent > div:last-child');
$('#main div:last-child').before("yourhtmlhere");

http://api.jquery.com/before/

Use insert Before. 使用插入之前。 Refer This for more. 有关更多信息,请参阅

var insertedElement = parentElement.insertBefore(newElement, referenceElement);

You can use the :last pseudo selector and the .before() method 您可以使用:last伪选择器和.before()方法

Here's a fiddle : http://jsfiddle.net/Aq6eu/ 这是一个小提琴: http : //jsfiddle.net/Aq6eu/

<div id='parent'>
    <div> child div 1</div>
    <div> child div 2</div>
    <div> child div 3</div>
    <div> child div 4</div>
    <div> child div 5</div>
</div>

$('#parent div:last').before('some text goes here ')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM