Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove last element from div?

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

like image 535
adolzi Avatar asked May 27 '15 20:05

adolzi


2 Answers

<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();
like image 78
Cliff Gunn Avatar answered Nov 12 '22 04:11

Cliff Gunn


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();
like image 27
Luka Krajnc Avatar answered Nov 12 '22 02:11

Luka Krajnc