Add element after specific list item

Viewed 107

I have a list of tabs set up like this. All tabs have a class tab_<number> and the active tab also has an extra class tab_active

Below these tabs there is a div that shows the dynamic content based on which tab is active

<div class="tab_content">xxx</div>

What I'm trying to do is insert the div tab_content below the active tab.

This works, but only on the second click on the tab, which I don't understand why.

The second script I tried, was looping through the different tabs and trying to insert the div like this, but this only works on the last item, because it just loops through it.

/*
// I tried two solutions, this was my first
jQuery(".tabs li").click(function() {
  jQuery(".tab_content").insertAfter(jQuery(".tab_active"));
});
*/

// second
var i;

for (i = 0; i < jQuery('.tabs li').length - 1; i++) {
  jQuery(".tab_" + i).click(function() {
    jQuery(".tab_content").insertAfter(jQuery(".tab_" + i));

  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="tabs">
  <li class="tab_0 tab_active"><a href="#">1</a></li>
  <li class="tab_1"><a href="#">2</a></li>
  <li class="tab_2"><a href="#">3</a></li>
  <li class="tab_3"><a href="#">4</a></li>
  <li class="tab_4"><a href="#">5</a></li>
</ul>
<div class="tab_content">xxx</div>

Can you guys/gals see what I'm doing wrong?

Much appreciated!

1 Answers
  • this can be done in something like following way.
  • Note though that if there are more tab_* elements in page then update the selector to be more stricter as needed to prevent selecting unexpected element.

$("[class^=tab_]").click(function(){
  $(this).append($(".tab_content"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="tabs">
    <li class="tab_0 tab_active"><a href="#">1</a></li>
    <li class="tab_1"><a href="#">2</a></li>
    <li class="tab_2"><a href="#">3</a></li>
    <li class="tab_3"><a href="#">4</a></li>
    <li class="tab_4"><a href="#">5</a></li>
</ul>

<div class="tab_content">xxx</div>

Related