I want to select a menu button depending on current page.
The traditional way is to use i++ to iterate the "list". I want to avoid this, because it is almost unreadable to a newbie:
(function() {
var anchors = document.querySelectorAll('.nav a'),
current = window.location.href;
for (var i = 0; i < anchors.length; i++) {
if (current.indexOf(anchors[i].href) != -1) {
anchors[i].classList.add("active");
}
}
})();
Less traditional way. More readable:
const navbtn = document.querySelectorAll('.navbtn');
var current = window.location.href;
(function() {
navbtn.forEach(myFunction);
function myFunction(el) {
if (current.indexOf(el.href) != -1) {
el.classList.add("active");
}
}
})();
But I am searching for ways to do it even more readable and using less rows. I have search but found no simpler ways to do this.
Is there simpler or more readable ways?