diff --git a/generic_assets/js/promote-data-aria-attributes.js b/generic_assets/js/promote-data-aria-attributes.js new file mode 100644 index 00000000..ace70b37 --- /dev/null +++ b/generic_assets/js/promote-data-aria-attributes.js @@ -0,0 +1,33 @@ +/** + * Copy `data-aria-*` attributes to matching `aria-*` on the same nodes. + * For HTML saved through WYSIWYG editors that strip unprefixed ARIA on publish. + * + * @param {ParentNode | null | undefined} [root=document] + */ +export default function promoteDataAriaAttributes(root = document) { + if (!root) { + return; + } + + const elements = + root instanceof Document + ? root.querySelectorAll('*') + : root instanceof Element + ? [ root, ...root.querySelectorAll('*') ] + : []; + + for (const el of elements) { + if (!(el instanceof Element)) { + continue; + } + for (const attr of [ ...el.attributes ]) { + if (!attr.name.startsWith('data-aria-')) { + continue; + } + el.setAttribute( + 'aria-' + attr.name.slice('data-aria-'.length), + attr.value + ); + } + } +}