[英]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();
});
結帳小提琴:
嘗試使用.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');
使用start
和end
slice()刪除前3個元素,例如
$('#fullContainer').children().slice(0,3).remove();// remove first 3 elements
要獲取first
和second
元素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.