akmur
akmur

Reputation: 1635

Removing and prepending in jQuery

I am trying to achieve a simple unordered list, with the following behaviour. When a list item is clicked, it needs to go on top of the list.

I managed to do it by assigning the element to a variable, removing "this" (the clicked item) and prepending my element variable.

This seems to work. Only once.

I guess this is because the elements are removed from the DOM, and the new ones are not "detected". WHat is the right way to do it?

Here's my simple code:

$('ul.selekta li').on('click', function() {
  var element = $(this);
  $(this).remove();
  $('ul.selekta').prepend(element);
});

Any help is super appreciated!

Upvotes: 0

Views: 134

Answers (1)

adeneo
adeneo

Reputation: 318182

That's because you're removing the element, just prepend it :

$('ul.selekta li').on('click', function() {
    $(this).prependTo('ul.selekta');
});

FIDDLE

Upvotes: 3

Related Questions