JavaScript(脱jQuery)
ナビゲーションに「current(カレント)」を付与する
現在のページのURLと各ナビゲーションリンクのURLを比較し、一致した場合に「class="is-current"」を追加する
HTML
javascript
document.addEventListener('DOMContentLoaded', () => {
// 現在のページのパスを取得して、index.htmlを除去
const currentPath = window.location.pathname.replace(/index\.html$/, '');
//ナビゲーションリンクを取得します
const navLinks = document.querySelectorAll('.nav__item a');
//リンクの href 属性値を取得します
navLinks.forEach(link => {
const linkPath = link.getAttribute('href').replace(/index\.html$/, '');
// スラッシュの整合性を揃えてから startsWith 判定
const normalizedLinkPath = linkPath.endsWith('/') ? linkPath : linkPath + '/';
const normalizedCurrentPath = currentPath.endsWith('/') ? currentPath : currentPath + '/';
if (normalizedCurrentPath.startsWith(normalizedLinkPath)) {
//[.nav__item a] にクラスを付与する場合
link.classList.add('is-current');
// linkの親 li.nav__item にクラスを付与する場合
const parentLi = link.closest('.nav__item');
if (parentLi) {
parentLi.classList.add('is-current');
}
}
});
});