skip to Main Content

Here I have a navigation items in a list which are in the specified order. I’m using JavaScript to change the order based on the condition. But I’m unable to get the order I’m trying to achieve.

actual order

Nav01
Nav02
Nav03
Nav04
Nav05
mynav

expected nav order

mynav
Nav01
Nav02
Nav03
Nav04
Nav05

What i’m getting

Nav02
Nav03
Nav04
Nav05
Nav01
mynav

html:

<ul>
    <li><a href="" class="nav-menu__item-link nav-menu__item-link--level-1 d-block d-lg-inline-block text-uppercase">Nav01</a></li>
    <li><a href="" class="nav-menu__item-link nav-menu__item-link--level-1 d-block d-lg-inline-block text-uppercase">Nav02</a></li>
    <li><a href="" class="nav-menu__item-link nav-menu__item-link--level-1 d-block d-lg-inline-block text-uppercase">Nav03</a></li>
    <li><a href="" class="nav-menu__item-link nav-menu__item-link--level-1 d-block d-lg-inline-block text-uppercase">Nav04</a></li>
    <li><a href="" class="nav-menu__item-link nav-menu__item-link--level-1 d-block d-lg-inline-block text-uppercase">Nav05</a></li>
    <li><a href="" class="nav-menu__item-link nav-menu__item-link--level-1 d-block d-lg-inline-block text-uppercase">mynav</a></li>
  </ul>

JS:

  var country = "NZ"
  
  if(country === 'NZ'){
    var firstMenuItem = $('a.nav-menu__item-link.nav-menu__item-link--level-1:contains("Nav01")').parent();
    var mynav = $('a.nav-menu__item-link.nav-menu__item-link--level-1:contains("mynav")').parent();
    mynav.before(firstMenuItem);    
  }

2

Answers


  1. .before(content) inserts content that is specified by parameter (in your case it is firstMenuItem) and inserts it before elements in a set you are calling method for (in your case it is mynav).

    So, if you want to use .before, you need to swap context and parameter like this:

    firstMenuItem.before(mynav)
    

    Please note, that if your intention is to move mynav to start of the list, it is better to specifically do so, in case items in your list would change their default positions. It can be achieved with mynav.prependTo(target) method, where target is your list.

    Login or Signup to reply.
  2. Use CSS.
    There’s no need to use JavaScript in order to just change the position of a last element – to first.
    Assign the parent a class and use CSS flex and order

    .nav-list {
      display: flex;
      flex-direction: column;
    }
    .nav-list li:last-child {
      order: -1;
    }
    <ul class="nav-list">
      <li><a href="#!">Nav01</a></li>
      <li><a href="#!">Nav02</a></li>
      <li><a href="#!">Nav03</a></li>
      <li><a href="#!">Nav04</a></li>
      <li><a href="#!">Nav05</a></li>
      <li><a href="#!">mynav</a></li>
    </ul>

    Ordering flex items (MDN)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search