简体   繁体   中英

jQuery wrap element inside a <li> and then appendTo

I am trying when wrap two <a> elements inside a <li> then to move them to another div . Now everytime when resize the window, and two new empty <li> are added. How to fix it ?

$(document).ready(appendBtns);
$(window).resize(appendBtns);

function appendBtns() {
    if($(window).innerWidth() < 768) {
       $('.btn').wrap('<li>').parent().appendTo('.main-nav ul')
    }
}

if your .main-nav ul has no other li elements in it just empty it before you add as I did as follows:

$(document).ready(appendBtns);
$(window).resize(appendBtns);

function appendBtns() {
    if($(window).innerWidth() < 768) {
       $('.main-nav ul').html(''); //add this line
       $('.btn').wrap('<li>').parent().appendTo('.main-nav ul')
    }
}

Note: This is the use case if your UL doen't has no other li's except the ones you are appending

Every time you resize your window, you create two new li. I would change your code to so it checks if the buttons have already been moved:

 $(document).ready(appendBtns); $(window).resize(appendBtns); var $navUl = $('.main-nav ul'); // do your selector here and cache in var for better performance var $buttons = $('.btn'); function appendBtns() { if ($(window).innerWidth() < 768 && !$buttons.closest('.main-nav').length) { // check to see if buttons have already been moved $navUl.append($buttons.wrap('<li></li>').parent()) } } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav class="main-nav"> <ul></ul> </nav> <a href="#" class="btn">test</a> <a href="#" class="btn">test 1</a> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM