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
.before(content)
inserts content that is specified by parameter (in your case it isfirstMenuItem
) and inserts it before elements in a set you are calling method for (in your case it ismynav
).So, if you want to use
.before
, you need to swap context and parameter like this: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 withmynav.prependTo(target)
method, wheretarget
is your list.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
Ordering flex items (MDN)