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

162
Views
DOMContentLoaded event not working in SPA route change

I have a SPA code where i use the history api and ES6 classes to insert html content into the DOM dynamically.

I have used event listeners such as DOMContentLoaded and checking of location paths before performing scripts but still the content is undefined.

//probably be fetching from a source
document.addEventListener("DOMContentLoaded",() => {
    // function truncateText(text,length) {
    //  if (text.length > length) {
    //      const truncatedText = text.substr(0,length);
    //      return truncatedText + "..."
    //  }
    //  return text;
    // }
    if (window.location.pathname == "/dashboard/posts") {
        const posts = document.querySelectorAll('.post'); //undefined but still exists
        console.log(posts.length == 0 ? false : true)

        posts.forEach((post) => {
            console.log("ran")
            const postTextH = post.children[0].children[1].children[0]
            const postText = post.children[0].children[1].children[1]
            console.log(postText,postTextH + "here")

            postText.innerText = truncateText("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco",150)
            postTextH.innerText = truncateText("How to never give up!",70)
        })
    }
})

So my question is how can i run this function after the content in the page is properly loaded and get the posts from the dom.

This is the repo I am using (the structure is same) SPA using history api and ES6 classes

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you have a SPA application, it means DOMContentLoaded event will be triggered once, when the app is ready (not when you navigate on the routes).

By your logic, this code should be triggered when the location history is changed. You could try to change your DOMContentLoaded event listener to popstate:

window.addEventListener('popstate', function (event) {
    // The URL changed...
});
about 4 years ago · Juan Pablo Isaza Report
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!