简体   繁体   中英

Reorder HTML List with Javascript or JQuery

I'm seeking help to see if it's possible to reorder the items in a navigation bar. The bar itself is created by a module within a CMS that is locked to editing.

As such, I'd like to reorder the "buttons" so that the 4th option will move to be the 1st in the menu bar.

The locked module creates the following HTML:

<div class="navigation-primary">
    <ul>
        <li><a href="/1" class="nav-link">AAA</a></li>
        <li><a href="/2" class="nav-link">BBB</a></li>
        <li><a href="/3" class="nav-link">CCC</a></li>
        <li><a href="/4" class="nav-link trigger">DDD</a></li>
        </ul>
</div>

Could I accomplish this with Javascript or jQuery?

Use document.querySelectorAll() to get the list items, and a reference to the ul . Then prepend the last list item to the ul :

 var listItems = document.querySelectorAll('.navigation-primary li'); document.querySelector('.navigation-primary > ul').prepend(listItems[listItems.length - 1]); 
 <div class="navigation-primary"> <ul> <li><a href="/1" class="nav-link">AAA</a></li> <li><a href="/2" class="nav-link">BBB</a></li> <li><a href="/3" class="nav-link">CCC</a></li> <li><a href="/4" class="nav-link trigger">DDD</a></li> </ul> </div> 

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