How to add a submenu toggle button inside all “li” elements that have a submenu?

I managed to solve this:

Create the function

So I created a new custom walker function in functions.php and copied all the code of the core wp nav walker function (wp-includes/class-walker-nav-menu.php).

Check for a menu item that has children

I then added this array_search in public function start_el to check if the parent element has the class “menu-item-has-children”:

$has_children = array_search ( 'menu-item-has-children' , $classes );

Output the toggle button

I then output the collapse element at the end of the start_el function if $has_children is true:

if($has_children != false) :
    $item_output .= '<div class="toggle-button"></div>';
endif;

Making it all work

I then added jQuery to toggle a class on the parent element of the toggle button.

jQuery(".toggle-button").click( function (){
    $(this).parent().toggleClass("menu-collapsed");
});

This works perfectly, but is there a better way to check if the menu item has children? Searching for a class name just doesn’t feel like the best solution.