I'm currently working with Bootstrap 4 and I am attempting to dynamically add the class active
to my nav-item
elements when their href
attribute matches the current URL.
In my HTML code, I have implemented a simple URL generator as follows:
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{{ url('/brands') }}" role="button">Brands</a>
</li>
<!-- ... -->
</ul>
To compare the links with the current URL, I used a jQuery method:
$('.navbar-nav .nav-item .nav-link').each( () => {
// If the current path matches the link URL...
if ($(this).attr('href').indexOf(location.pathname) !== 1) {
// ...then add the 'active' class to the parent 'nav-item'
$(this).parent().addClass('active')
}
})
However, I encountered an issue where $(this).attr('href')
was returning undefined
, likely due to it being a generated URL, resulting in the nav-item
not receiving the active
class.
EDIT: Currently, the URL is very basic without any parameters, such as:
If anyone has a solution to this problem, your input would be greatly appreciated. Thank you in advance.