Skip to content

Instantly share code, notes, and snippets.

@cmbaughman
Created February 4, 2026 00:35
Show Gist options
  • Select an option

  • Save cmbaughman/620b7d44034562fde33e6dced7d1ea71 to your computer and use it in GitHub Desktop.

Select an option

Save cmbaughman/620b7d44034562fde33e6dced7d1ea71 to your computer and use it in GitHub Desktop.
Replace ® with superscript version
window.addEventListener('DOMContentLoaded', () => {
const walk = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
null,
false
);
const reg = /®/g;
let node;
// Use a list to avoid mutating the DOM while walking
const nodesToReplace = [];
while (node = walk.nextNode()) {
if (node.parentElement.tagName !== 'SUP' && node.nodeValue.includes('®')) {
nodesToReplace.push(node);
}
}
nodesToReplace.forEach(textNode => {
const parent = textNode.parentElement;
const parts = textNode.nodeValue.split(reg);
const fragment = document.createDocumentFragment();
parts.forEach((part, i) => {
fragment.appendChild(document.createTextNode(part));
if (i < parts.length - 1) {
const sup = document.createElement('sup');
sup.textContent = '®';
fragment.appendChild(sup);
}
});
parent.replaceChild(fragment, textNode);
});
});
@cmbaughman
Copy link
Author

cmbaughman commented Feb 4, 2026

Alternative version:

// Hell yeah treewalker!
document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT).nextNode();

const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
let n;
while (n = walk.nextNode()) {
  if (n.nodeValue.includes('®') && n.parentElement.tagName !== 'SUP') {
    n.replaceWith(...n.nodeValue.split(/(®)/g).map(t => 
      t === '®' ? Object.assign(document.createElement('sup'), {textContent: '®'}) : t
    ));
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment