JavaScript:删除上课的最后一个孩子

时间:2016-12-08 11:09:58

标签: javascript

所以我试图用特定的类删除我的DOM中的最后一个元素但是我运气不好。我可以完全删除该类,但不能单独删除它。任何帮助都会很棒

<div class="banner banner-1"></div>
<div class="banner banner-2"></div>
<div class="banner banner-3"></div>
<div class="banner banner-4"></div>
<div class="banner banner-3"></div>
<div class="banner banner-5"></div>

抱歉,忘记将我的其他代码粘贴到:

var classToRemove = 'banner-3';

document.removeChild(document.getElementsByClassName(classToRemove))

例如,我有6个横幅,但重复横幅3。如何获取最后一个banner-3并删除它而不影响第一个?

谢谢!

2 个答案:

答案 0 :(得分:1)

// access all elements by class
var ele = document.getElementsByClassName('banner');
// find last element
var lastEle = ele[ ele.length-1 ];
//--- do what you need to do with the element

var ele = document.querySelectorAll(".banner .banner_3");
var lastEle = ele[ ele.length-1 ];
lastEle.parentNode.removeChild(lastEle);

答案 1 :(得分:0)

您可以通过getElementsByClassName获取列表,然后在迭代中删除它们但不首先删除

for(var i=1;i<document.getElementsByClassName('banner-3').length;i++)
  document.getElementsByClassName('banner-3')[i].remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="banner banner-1">1</div>
<div class="banner banner-2">2</div>
<div class="banner banner-3">3</div>
<div class="banner banner-4">4</div>
<div class="banner banner-3">3</div>
<div class="banner banner-5">5</div>