Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
How to get DOM elements added dynamically

I am using Anchorjs with Bootstrap scrollspy (or at least trying to!).

AnchorJS adds id to each element on 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 is initiated after 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
    }
});

However, I still get an a Uncaught DOMException:

Failed to execute 'querySelector' on 'Document': '#example-anchor' is not a valid selector.

This is presumably because document.getElementById('body') does not include the IDs set by AnchorJS.

How can I fix this? scrollspy.refresh() makes no difference.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!