If you want to add items dynamically at every page call, you can look this answer :
Dynamically add sub-categories to any category in the menu
And to add an element directly, you can try that for a custom link e.g. :
// create the new element
$post = [
'post_title' => "StackExchange " . date("H:i:s"),
"menu_order" => 700, // position in the menu
'post_type' => 'nav_menu_item',
'post_status' => 'publish',
];
$menu_item_db_id = wp_insert_post( $post );
update_post_meta( $menu_item_db_id, 'url', "https://wordpress.stackexchange.com/");
update_post_meta( $menu_item_db_id, 'type', "custom");
update_post_meta( $menu_item_db_id, '_menu_item_menu_item_parent', 0); // change to create a sub menu
// association to the menu
$menuLocations = get_nav_menu_locations();
$menuID = (int) $menuLocations['primary'];
wp_set_object_terms($menu_item_db_id, $menuID, "nav_menu");
wp_nav_menu_update_menu_items
but there is no documentation then it can be more difficult to do that (but not impossible)