How can I remove the last element from a div?

I have a list of descriptions, and after removing one of them, I would like to remove the last element from the div, rather than refresh the site. I don't really know javascript, so I would like to ask how my destroy.js.erb should look like? I can update the "descriptions" of the whole class using

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

      

but I'm wondering if there is a way to remove only the last item.

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

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

      

Thanks for any help

+3


source to share


3 answers


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

      

The next line of jQuery will remove "Item 3".



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

      

+9


source


Use a css selector :last-child

to remove it (found here ). Then use jQuery to remove the last element.

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

      

Here's a jsFiddle example:

html:



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

      

JavaScript:

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

      

+1


source


Use this if you want to remove the last div:

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

      

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

$('#mydiv:last-child')

      

0


source







All Articles