diff --git a/src/wp-includes/html-api/class-wp-html-tag-processor.php b/src/wp-includes/html-api/class-wp-html-tag-processor.php
index 0000000000..0000000000 100644
--- a/src/wp-includes/html-api/class-wp-html-tag-processor.php
+++ b/src/wp-includes/html-api/class-wp-html-tag-processor.php
@@ -2843,17 +2843,40 @@ class WP_HTML_Tag_Processor {
 	public function get_attribute_names_with_prefix( $prefix ): ?array {
 		if ( self::STATE_MATCHED_TAG !== $this->parser_state || $this->is_closing_tag ) {
 			return null;
 		}
+
+		/*
+		 * Make sure pending class changes are represented as attribute updates
+		 * before reading the current attribute names.
+		 */
+		$this->class_name_updates_to_attributes_updates();
+
 		$comparable = strtolower( $prefix );
-		$matches    = array();
+		$matches    = array();
+
 		foreach ( array_keys( $this->attributes ) as $attr_name ) {
 			if ( str_starts_with( $attr_name, $comparable ) ) {
-				$matches[] = $attr_name;
+				$matches[ $attr_name ] = true;
+			}
+		}
+
+		foreach ( $this->lexical_updates as $name => $update ) {
+			if ( ! is_string( $name ) ) {
+				continue;
+			}
+
+			if ( ! str_starts_with( $name, $comparable ) ) {
+				continue;
+			}
+
+			if ( '' === $update->text ) {
+				unset( $matches[ $name ] );
+				continue;
 			}
+
+			$matches[ $name ] = true;
 		}
-		return $matches;
+
+		return array_keys( $matches );
 	}
 
 	/**
