Skip to content

Instantly share code, notes, and snippets.

@scateu
Last active May 22, 2025 07:32
Show Gist options
  • Save scateu/e52ac30e51be3a181c3c39f052bf3b31 to your computer and use it in GitHub Desktop.
Save scateu/e52ac30e51be3a181c3c39f052bf3b31 to your computer and use it in GitHub Desktop.
Bookmarklet - Convert HTML <h2> tag into foldables
javascript:(function(){
function wrapContentBetweenH2s() {
const body = document.body;
const h2s = Array.from(body.getElementsByTagName('h2'));
h2s.forEach((h2, index) => {
const details = document.createElement('details');
const summary = document.createElement('summary');
summary.innerHTML = h2.innerHTML;
details.appendChild(summary);
let nextElement = h2.nextElementSibling;
while (nextElement && !['H1', 'H2', 'H3', 'H4', 'H5', 'H6'].includes(nextElement.tagName)) {
const current = nextElement;
nextElement = nextElement.nextElementSibling;
details.appendChild(current);
}
h2.parentNode.replaceChild(details, h2);
});
}
wrapContentBetweenH2s();
})();
javascript:(function(){
function wrapInDetails(el) {
var details = document.createElement('details');
var summary = document.createElement('summary');
summary.style.display = 'flex';
summary.style.alignItems = 'center';
summary.appendChild(el.cloneNode(true));
details.appendChild(summary);
while (el.nextElementSibling && !['H2', 'H3'].includes(el.nextElementSibling.tagName)) {
details.appendChild(el.nextElementSibling);
}
el.parentNode.replaceChild(details, el);
}
var headings = document.querySelectorAll('h2, h3');
headings.forEach(wrapInDetails);
var style = document.createElement('style');
style.textContent = 'details > summary { list-style: none; } details > summary::-webkit-details-marker { display: none; } details > summary::before { content: "▶"; margin-right: 0.5em; } details[open] > summary::before { content: "▼"; }';
document.head.appendChild(style);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment