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
CodePudding user response:
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...
});