6

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

$('.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

adolzi
  • 671
  • 2
  • 7
  • 15

4 Answers4

22
<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."

$('.parent').children().last().remove();
Cliff Gunn
  • 458
  • 2
  • 7
2

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

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

Here is jsFiddle example:

html:

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

JavaScript:

$("div :last-child").remove();
Luka Krajnc
  • 915
  • 1
  • 7
  • 21
0

Use this if you want to remove the last div:

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

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

$('#mydiv:last-child')
zeppelin
  • 451
  • 1
  • 4
  • 24
  • 1
    Misunderstanding of `:last-child`. Maybe this article about [:last-child](https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child) helps you. :) – Dennis98 Oct 25 '16 at 11:21
-1
<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

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

or you can also use

$("#child").css({"display": "none"});
  • This is just wrong. First, `.remove()` removes all matched elements, so it would remove every child, BUT your example markup is also invalid (multiple same IDs) and even in this case it's not correct, as it removes only the first child then. – Dennis98 Oct 11 '18 at 21:01