簡體   English   中英

如何使用jQuery刪除開始的div元素?

[英]how to remove starting div elements using jquery?

<div ="fullcontainer">
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
<div id="d"></div>
<div id="e"></div>

</div>

$('#fullContainer').children().slice(2).remove();

它給出結果:

<div ="fullcontainer">
<div id="a"></div>
<div id="b"></div>
</div>

如何獲得這樣的結果?

<div ="fullcontainer">

<div id="d"></div>
<div id="e"></div>

</div>

第二個問題,我得到倒數第二個div id像這樣:

$('#fullContainer div:last-child').attr('id');

$('#fullContainer div:nth-last-child(2)').attr('id');

如何獲得第一和第二個div ID?

您可以使用以下代碼刪除第一個div:

$(document).ready(function(){
    $("#fullcontainer div:first-child").remove();
});

結帳小提琴:

http://jsfiddle.net/aX83W/

嘗試使用.eq()

$('#fullContainer').children().eq(0)  //first div
$('#fullContainer').children().eq(1)  //second div
.
.
$('#fullContainer').children().eq(n)  //nth div

您需要的完整代碼,

var cache = $('#fullContainer').children();
cache.first().remove();  //removing the first one
cache.eq(cache.length - 2).attr('id'); // getting the id of the second one from the last.

對於新編輯,您可以嘗試像

   var cache = $('#fullContainer').children();
   cache.filter(':lt(' + (cache.length - 2) + ')').remove();

演示

首先刪除

$('#fullContainer').children().first().remove();

編號

$('#fullContainer div:first-child').attr('id');

$('#fullContainer div:nth-child(2)').attr('id');

使用startend slice()刪除前3個元素,例如

$('#fullContainer').children().slice(0,3).remove();// remove first 3 elements

要獲取firstsecond元素id嘗試使用eq-selector

$('#fullContainer div:eq(0)').attr('id');// first element id
$('#fullContainer div:eq(1)').attr('id');// second element id

或者您可以嘗試使用nth-child選擇器

$('#fullContainer div:nth-child(1)').attr('id');// first element id
$('#fullContainer div:nth-child(2)').attr('id');// second element id

請注意,請確保您的div-id為fullcontainer (您從div元素中丟失了ID),並且您正在jquery中使用fullContainer ,要使其正常工作,兩者必須相同。

演示版

$('#fullContainer div').eq(0).remove();

您可以使用:first或first(),甚至可以使用eq()運算符

$('#fullContainer div :first').remove()

要么

$('#fullContainer div').first().remove()

要么

$('#fullContainer div').eq(0).remove()
To remove first

$('#fullContainer').children().first().remove();

$('#fullContainer').children(div:nth-of-type(1)).remove();
$('#fullContainer').children(div:nth-of-type(1)).remove(); 
$('#fullContainer').children(div:nth-of-type(1)).remove();

甚至喜歡這樣

$('#fullContainer div:nth-child(1)').attr('id');
$('#fullContainer div:nth-child(2)').attr('id');
$('#fullContainer div:nth-child(n)').attr('id');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM