Skip to content

Instantly share code, notes, and snippets.

@scateu
Last active August 23, 2025 13:01
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);
})();
@magasine
Copy link

magasine commented Aug 20, 2025

Hello... great idea for a bookmarklet. Inspired by your code and with the help of AI, I was able to create this version. I'm sharing it in gratitude for the initial idea.

Foldable Tags

@scateu
Copy link
Author

scateu commented Aug 21, 2025

@magasine Very glad it helps! Thank you for the replied version. 🥳

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