diff --git a/src/wp-includes/category-template.php b/src/wp-includes/category-template.php
index fab2640c0b..ac992d6b3c 100644
--- a/src/wp-includes/category-template.php
+++ b/src/wp-includes/category-template.php
@@ -624,8 +624,9 @@ function wp_list_categories( $args = '' ) {
 		$output .= walk_category_tree( $categories, $depth, $r );
 	}
 
-	if ( $r['title_li'] && 'list' == $r['style'] )
+	if ( $r['title_li'] && 'list' == $r['style'] && ( ! empty( $categories ) || ! $r['hide_title_if_empty'] ) ) {
 		$output .= '</ul></li>';
+	}
 
 	/**
 	 * Filters the HTML output of a taxonomy list.
diff --git a/tests/phpunit/tests/category/wpListCategories.php b/tests/phpunit/tests/category/wpListCategories.php
index 061496a8a6..571dc04975 100644
--- a/tests/phpunit/tests/category/wpListCategories.php
+++ b/tests/phpunit/tests/category/wpListCategories.php
@@ -265,6 +265,22 @@ class Tests_Category_WpListCategories extends WP_UnitTestCase {
 		$this->assertContains( '<li class="categories">Categories', $found );
 	}
 
+	/**
+	 * @ticket 38839
+	 */
+	public function test_hide_title_if_empty_should_not_output_stray_closing_tags() {
+		$cat = self::factory()->category->create();
+
+		$found = wp_list_categories( array(
+			'echo' => false,
+			'show_option_none' => '',
+			'child_of' => 1,
+			'hide_title_if_empty' => true,
+		) );
+
+		$this->assertNotContains( '</ul></li>', $found );
+	}
+
 	/**
 	 * @ticket 12981
 	 */