Я создаю свой первый SPA, и я следую этому уроку: https://www.youtube.com/watch?v=wlVmmsMD28w&t=846s, просто я нашел его самым последним и наиболее информативным.
Все работает, если мне нравится его, но как только я изменяю его на html, я получаю эту ошибку ( Uncaught TypeError: Невозможно прочитать свойство 'classList' с нулевым ), как только я нажимаю на тег привязки.
// object
const app = {
pages: [], // property to save pages in
show: new Event('show'),
init: function() {
app.pages = document.querySelectorAll('.page');
//listener for show event, calling function
app.pages.forEach((pg)=> {
pg.addEventListener('show', app.pageShown);
})
//listener for click event, calling function
document.querySelectorAll('.nav-link').forEach((link)=>{
link.addEventListener('click', app.nav);
})
// showing on which page we are in the tab
history.replaceState({}, 'Home', '#home');
// handling the "back" button
window.addEventListener('popstate', app.poppin);
},
nav: function(ev){
ev.preventDefault();
let currentPage = ev.target.getAttribute('data-target');
document.querySelector('.active').classList.remove('active'); ////////// THE LINE ERROR IS APPEARING AT
document.getElementById(currentPage).classList.add('active');
console.log(currentPage);
history.pushState({}, currentPage, '#${currentPage}');
document.getElementById(currentPage).dispatchEvent(app.show);
},
pageShown: function(ev){
console.log('Page', ev.target.id, 'just shown');
},
poppin: function(ev){
console.log(location.hash, 'popstate event');
}
}
document.addEventListener('DOMContentLoaded', app.init);
и это мой html код:
<div class="page selected" id="home">
<div id="cell_1">
<a href="#" data-target="recipe" class="nav-link">
<img id="mainPic" src="./pictures/thai.jpg">
</a>
</div>
</div>
<div class="page" id="recipe">
<p>a</p>
</div>
Может кто-нибудь попытаться помочь мне, почему это происходит? Кстати, я не перенаправлен на другую страницу.