如何删除jquery或javascript

时间:2018-11-29 17:25:41

标签: javascript jquery html

我在ul中有多个li标签。这里我需要删除所有具有类'removeMe'的li标签,除了第一个具有'removeMe'类的li标签。这里这些标签可以是n number可以是2或3或4等。'这是第一个div 这是第一个div。我只能删除“ removeMe”类的第二个li。这是下面的代码。

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<span>Hi</span
<li class="abc212">This is the first div</li>
<li class="abc333">This is the first div</li>
<li class="removeMe">This is the first div</li>
<li class="removeMe">This is the SECOND div, should not show</li>
<li class="removeMe">This is the third div</li>
</ul>

脚本

$(document).ready(function(){
     $('li:nth-child(4).removeMe').hide();
});

4 个答案:

答案 0 :(得分:1)

您可以使用:gt()选择器

$('li.removeMe:gt(0)').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="abc212">This is the first div</li>
  <li class="abc333">This is the first div</li>
  <li class="removeMe">This is the first div</li>
  <li class="removeMe">This is the SECOND div, should not show</li>
  <li class="removeMe">This is the third div</li>
</ul>

答案 1 :(得分:1)

获取所有具有类removeMe的元素,并从索引1开始对其进行迭代,然后使用remove()删除该元素

let getAllRemoveMe = $('.removeMe');

for (let i = 1; i < getAllRemoveMe.length; i++) {
  getAllRemoveMe[i].remove()

}
.removeMe {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <span>Hi</span>
  <li class="abc212">This is the first div</li>
  <li class="abc333">This is the first div</li>
  <li class="removeMe">This is the first div</li>
  <li class="removeMe">This is the SECOND div, should not show</li>
  <li class="removeMe">This is the third div</li>
</ul>

答案 2 :(得分:-1)

使用香草JS:

var lists = document.querySelectorAll("li.removeMe");

for(var i = 1; i < lists.length; i++) {
  lists[i].parentElement.removeChild(lists[i]);
}
<ul>
  <span>Hi</span>
  <li class="abc212">This is the first div</li>
  <li class="abc333">This is the first div</li>
  <li class="removeMe">This is the first div</li>
  <li class="removeMe">This is the SECOND div, should not show</li>
  <li class="removeMe">This is the third div</li>
</ul>

答案 3 :(得分:-1)

您必须使用remove()删除任何element。尝试使用此:

$('.removeMe').each(function(index){
   if(index !=1)
       $(this).remove();
});

希望这对您有帮助