0

I'm checking to see if element is last in the container div by getting length on next element with class .item (if there is such element, it means that I am currently not at the end of the container div)

if($(this).next('.item').length < 1) {
  console.log('element is last');
}

In case if it is last, I want to move it up, i.e insert it before previous .item so it now becomes second last.

I looked into .insertBefore() , however I don't explicitly know which "before" element to target.

Ilja
  • 44,142
  • 92
  • 275
  • 498
  • Maybe this can help: http://stackoverflow.com/questions/3362747/how-to-insert-an-element-at-selected-position-in-html-document – AlwaysNull Dec 02 '15 at 17:02

1 Answers1

1

You can use the :last selector to get the last element in a matched set. From there you can use insertBefore() and prev() to move it as required. Try this:

var $last = $('.item:last');
$last.insertBefore($last.prev());

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339