javascript 如何从div中删除最后一个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30492918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:16:41  来源:igfitidea点击:

How to remove last element from div?

javascriptruby-on-rails

提问by adolzi

I have list of descriptions and after remove one of them, I'd like to remove last element from div, not refreshing site. I don't know javascript in fact, so I'd like to ask how should my destroy.js.erb looks like? I can refresh whole class "descriptions" using

我有描述列表,删除其中一个后,我想从 div 中删除最后一个元素,而不是刷新站点。我其实不懂javascript,所以我想问一下我的destroy.js.erb应该是什么样子的?我可以使用刷新整个班级的“描述”

$('.descriptions').load(location.href + " .descriptions");

but I'm interested, if there is way to remove only last element.

但我很感兴趣,如果有办法只删除最后一个元素。

  <div class="descriptions">
       <%= render @descriptions %> 
  </div>

 //_description.html.erb
 <div class="description-field">
        <%= @description.text %>
 </div>

Thank you for any help

感谢您的任何帮助

回答by Cliff Gunn

<div class="parent">
    <div class="child">
        Item 1
    </div>
    <div class="child">
        Item 2
    </div>
    <div class="child">
        Item 3
    </div>
</div>

The following line of jQuery would delete "Item 3."

以下 jQuery 行将删除“Item 3”。

$('.parent').children().last().remove();

回答by Luka Krajnc

Use css selector :last-childto remove it (found here). Then use jQuery to remove last element.

使用 css 选择器:last-child将其删除(在此处找到)。然后使用 jQuery 删除最后一个元素。

$(".yourdiv :last-child").remove();

Here is jsFiddleexample:

这是jsFiddle示例:

html:

html:

<div>
    <p> Hello </p>
    <p> World </p>
    <p> last element </p>
</div>

JavaScript:

JavaScript:

$("div :last-child").remove();

回答by zeppelin

Use this if you want to remove the last div:

如果要删除最后一个 div,请使用此选项:

$("div:last").remove(); 

Use this if you want to remove the last sibling of some div with id "#mydiv"

如果要删除某个 id 为“#mydiv”的 div 的最后一个兄弟,请使用此选项

$('#mydiv:last-child')

回答by Brian Ombisa

<div id="parent">
    <div id="child">
        Item 1
    </div>
    <div id="child">
        Item 2
    </div>
    <div id="child">
        Item 3
    </div>
</div>

The following is a JQuery code that removes the last child item 3

以下是移除最后一个子项3的JQuery代码

$("#child").remove();

or you can also use

或者你也可以使用

$("#child").css({"display": "none"});