I have a list of submenus and I want to move each 4 child <li></li>
to a new parent <ul></ul>
separately
<ul class="sub_menu">
<li>Menu 1</li>
<li>Menu 2</li>
<li>Menu 3</li>
<li>Menu 4</li>
<li>Menu 5</li>
<li>Menu 6</li>
<li>Menu 7</li>
<li>Menu 8</li>
</ul>
<div class="container_row">
<div class="row">
<div class="col1 col_3">
<div class="wrap">
<ul>
</ul>
</div>
</div>
<div class="col1 col_3">
<div class="wrap">
<ul>
</ul>
</div>
</div>
</div>
</div>
The final output that I am looking for is written below:
<div class="container_row">
<div class="row">
<div class="col1 col_3">
<div class="wrap">
<ul>
<li>Menu 1</li>
<li>Menu 2</li>
<li>Menu 3</li>
<li>Menu 4</li>
</ul>
</div>
</div>
<div class="col1 col_3">
<div class="wrap">
<ul>
<li>Menu 5</li>
<li>Menu 6</li>
<li>Menu 7</li>
<li>Menu 8</li>
</ul>
</div>
</div>
</div>
</div>
The code I've tried so far is
$(document).ready(function() {
$(".container_row .wrap ul").append($(".sub_menu li"));
});
Do you have any idea how to achieve the final output?
This is kind of what you are trying to do I think.
$('ul.sub_menu li').each(function (i) {
const index = Math.trunc(i / 4);
$(this).detach().appendTo($('div.wrap ul').get(index));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="sub_menu">
<li>Menu 1</li>
<li>Menu 2</li>
<li>Menu 3</li>
<li>Menu 4</li>
<li>Menu 5</li>
<li>Menu 6</li>
<li>Menu 7</li>
<li>Menu 8</li>
</ul>
<div class="container_row">
<div class="row">
<div class="col1 col_3">
<div class="wrap">
<ul></ul>
</div>
</div>
<div class="col1 col_3">
<div class="wrap">
<ul></ul>
</div>
</div>
</div>
</div>
You can set id for div and use each method like this
$(document).ready(function() {
var length = $(".sub_menu li").length;
//console.log(length)
$(".sub_menu li").each(function(index, item){
if(index < length/2){
$("#first ul").append(item);
//console.log($(".container_row .wrap ul:nth-child(0)").length)
}else{
$("#second ul").append(item);
//console.log(index)
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="sub_menu">
<li>Menu 1</li>
<li>Menu 2</li>
<li>Menu 3</li>
<li>Menu 4</li>
<li>Menu 5</li>
<li>Menu 6</li>
<li>Menu 7</li>
<li>Menu 8</li>
</ul>
<div class="container_row">
<div class="row">
<div class="col1 col_3">
<div class="wrap" id="first">
<ul>
</ul>
</div>
</div>
<div class="col1 col_3">
<div class="wrap" id="second">
<ul>
</ul>
</div>
</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With