Sam Assoum Sam Assoum - 1 month ago 11
Javascript Question

Make element the first child of it's parent list, on click

I have a ul list with 4 list items in it. The list items have IDs named #one, #two, #three and #four:

<ul class="home_slider">
<li id="one">one</li>
<li id="two">two</li>
<li id="three">three</li>
<li id="four">four</li>
</ul>


There is also another ul list with 4 corresponding list items:

<ul class="btn_wrap">
<li class="btn" id="btn-01"></li>
<li class="btn" id="btn-02"></li>
<li class="btn" id="btn-03"></li>
<li class="btn" id="btn-04"></li>
</ul>


The four list items in the second ul list act as buttons using jQuery click.

The buttons correspond to the first ul list's items, for example #btn-01 manipulates #one.

The question

I want to make it so when you click on #btn-01, it makes #one become the first-child of its parent ul "home_slider".

Same logic applies to the other buttons, so when you click #btn-02 it would make #two become the first child of "home_slider".

Here is a JS Fiddle with comments where I imagine the code needs to go:

JS Fiddle

There is slightly more going on in the fiddle, such as classes being added on click, but for simplicity's sake, I left that out as it doesn't really pertain to the question.

Answer

There are a few things that will help you here, I altered your fiddle as shown:

HTML

<ul class="home_slider">
  <li data-id="btn-01" id="one">one</li>
  <li data-id="btn-02" id="two">two</li>
  <li data-id="btn-03" id="three">three</li>
  <li data-id="btn-04" id="four">four</li>
</ul>

<ul class="btn_wrap">
  <li class="btn" id="btn-01"></li>
  <li class="btn" id="btn-02"></li>
  <li class="btn" id="btn-03"></li>
  <li class="btn" id="btn-04"></li>
</ul>

JS

jQuery('.btn').click(function() {
  var target = '[data-id="' + $(this).attr('id') + '"]';
  $('.btn').removeClass('btn-selected');
  $(this).addClass('btn-selected');

  $(target).prependTo('.home_slider');

  $('.home_slider > li').removeClass('active');
  $(target).addClass('active');
});
Comments