Regular Expression
Assuming the HTML elements are directly in the <body>
then regular expression back-references can also remove the consecutive duplicates, here facilitated by jQuery:
const jqContainer = jQuery("body");
jqContainer
.html(
jqContainer
.html()
.replace(/(<span>[^<>]+<\/span>)+/g, "$1")
)
;
NOTE: The regular expression in this case matches all consecutive duplicate <span>
elements containing text regardless of what that text is. If you wanted to match <span>
with specific text within then replace [^<>]+
with the text to be replaced, e.g. x
CSS
The following may not be applicable in this context, but if the goal is to remove the consecutive duplicate elements for presentation purposes, and if CSS is applicable, then the following CSS will stop the consecutive duplicate spans from being displayed:
span + span {
display: none;
}