Estoy usando Anchorjs con Bootstrap scrollspy (¡o al menos intento!).
AnchorJS agrega id a cada elemento en DOMContentLoaded :
document.addEventListener('DOMContentLoaded', function (event) { const anchors = new AnchorJS(); anchors.add('.post h2:not(:empty), .post h3:not(:empty), .post' + ' h4:not(:empty), .post h5:not(:empty), .post h6:not(:empty),' + ' .post p:not(:empty)'); anchors.options = {icon: '#'}; }); ScrollSpy se inicia después de complete readystatechange :
document.addEventListener('readystatechange', event => { if (event.target.readyState === "complete") { const scrollSpyContentEl = document.getElementById('body') const scrollSpy = bootstrap.ScrollSpy.getOrCreateInstance(scrollSpyContentEl, { target: '#anchor-list', offset: 36, }) // Returns a Bootstrap scrollspy instance } }); Sin embargo, sigo recibiendo una Uncaught DOMException :
No se pudo ejecutar 'querySelector' en 'Documento': '#example-anchor' no es un selector válido.
Presumiblemente, esto se debe a document.getElementById('body') no incluye los ID establecidos por AnchorJS.
¿Cómo puedo arreglar esto? scrollspy.refresh() no hace ninguna diferencia.