Jack1991 Jack1991 - 7 months ago 15
Javascript Question

How to use JQuery to insert a class into an unordered list item before its child sub-menu?

I'm working on a multi-level mobile navigation menu with the Wordpress PHP menu function and I'm having difficulty inserting a span button (to open sub-menus) into a parent list item without it appearing after the sub-menu.

At the moment it is appearing as follows in the inspect element markup:

<li class=“menu-item menu-item-post_type menu-item-object-page menu-item-has-children menu-item-463”> ==$0
<a href=“http://www.mywebsite.co.uk/page/“>Page</a>
<ul class=“sub-menu”>…</ul>
<span class=“submenu-button”>+</span>
</li>


I would like to be able to insert it before the ul class if possible, like this:

<li class=“menu-item menu-item-post_type menu-item-object-page menu-item-has-children menu-item-463”> ==$0
<a href=“http://www.mywebsite.co.uk/page/“>Page</a>
<span class=“submenu-button”>+</span>
<ul class=“sub-menu”>…</ul>
</li>


The JQuery I'm currently using to add the span/button is as follows:

$('nav.main-menu#mobile ul li:not(.hide-mobile) ul').parent('li').append('<span class="submenu-button">+</span>');


I have tried using
prepend
instead of
append
, but this moved it in front of the
li a
tag as well as the
ul ul
, which is something I want to avoid.

Is there a better way of doing this?

Answer

use jquery before

$('.sub-menu').before('<span class=“submenu-button”>+</span>');

OR insertBefore

$( "<span class='submenu-button'>+</span>" ).insertBefore( ".sub-menu" );