Skip to content

Instantly share code, notes, and snippets.

@aquilax
Created May 30, 2021 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aquilax/71b4b26ff5dfb0e92f22fa8a36e68dff to your computer and use it in GitHub Desktop.
Save aquilax/71b4b26ff5dfb0e92f22fa8a36e68dff to your computer and use it in GitHub Desktop.
Inserts heading navigation for long documents
const datalist = document.createElement('datalist');
datalist.setAttribute('id', 'header-list');
Array.from(document.querySelectorAll("h1, h2, h3, h4, h5, h6")).forEach(headerNode => {
const id = headerNode.id || headerNode.innerText.replace(/\W/g, '_') || Math.random();
headerNode.setAttribute('id', id);
const option = document.createElement('option');
option.setAttribute('value', headerNode.innerText);
option.dataset.target = id;
datalist.appendChild(option);
});
const input = document.createElement('input');
input.setAttribute('list', 'header-list');
input.addEventListener('change', event => {
const value = input.value;
const option = Array.from(datalist.children).find(option => option.value === value);
if (option.dataset.target) {
location.hash = "#" + option.dataset.target;
}
});
const container = document.createElement('div');
container.appendChild(input);
container.appendChild(datalist);
document.body.insertBefore(container, document.body.firstChild);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment