如何使用jquery删除元素

How to remove element using jquery

本文关键字:元素 删除 jquery 何使用      更新时间:2024-05-31

我有一个div,它包含:

<div id="div1">
        <span class="input-group-addon">Span1</span>
        <span class="input-group-addon">Span2</span>
        <span class="input-group-addon">Span3</span>
        <span class="input-group-addon npsButton"><a target='_blank' href='nps.html'>Link</a></span>
</div>

我尝试使用:$("#div1").remove("span.npsButton");删除最后一个跨度.npsButton,但它不起作用。当我通过控制台$("#div1span.npsButton")进行检查时,它返回[]。有人能告诉我如何删除这个span

使用后代选择器

$('#div1 .npsButton').remove()
//      ^           Note the space here

CCD_ 4将选择具有ID的元素作为CCD_ 5和类别CCD_。由于没有满足此选择器的元素,它将返回空数组。


要删除DOM中具有该类的所有元素,

$('.npsButton').remove();

使用

$("span.npsButton").remove();

除了使用classid进行选择外,您还可以通过其他方式选择最后一个子

  1. :最后一个子选择器
  2. .last()
  3. :nth-last-child()

在下面的代码段中,我使用:last-child,它将选择作为父的最后一个子元素的所有元素

$( "div#div1 span:last-child" ).remove()

工作示例

这样尝试

$( "#div1 span" ).last().hide();