Skip to content

Instantly share code, notes, and snippets.

@robkorv
Created October 2, 2025 15:07
Show Gist options
  • Select an option

  • Save robkorv/ac8e73ab8e0d72162652daa53ea93229 to your computer and use it in GitHub Desktop.

Select an option

Save robkorv/ac8e73ab8e0d72162652daa53ea93229 to your computer and use it in GitHub Desktop.
merge descendant spans that have the same style (might be needed with ckeditor content)
// create an array from spans that are a direct child of a non-span element
Array.from(document.querySelectorAll("*:not(span) > span"))
// filter out those that do not have a span in it's descendants
.filter((x) => x.querySelectorAll("span").length)
.map((x) =>
// map the result to arrays of descendent spans
Array.from(x.querySelectorAll("span"))
// reverse the array, so we work from the deepest span
.toReversed()
.filter(
(x) =>
// filter out spans which aren't the only child of their parent
x.parentElement.children.length === 1 &&
// filter out spans which parent isn't a span
x.parentElement.tagName === "SPAN" &&
// filter out spans that do not have cssText
x.style.cssText &&
// filter out spans where the parent does not have cssText
x.parentElement.style.cssText &&
// filter out spans where the cssText is not the same as the parent
x.style.cssText === x.parentElement.style.cssText
)
)
// filter out empty arrays from the mapped result
.filter((x) => x.length)
// for each nested span tree
.forEach((x) => {
x.forEach((x) => {
// replace it's the parent of the last descendent with itself
if (x.parentElement) x.parentElement.replaceWith(x);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment