Looking for assistance with a javascript and DOM code improvement.
I currently have a page navigation bar structured like this (used on certain pages):
<div id="pagebar">
<a href="iraq_pixra1.html">1</a>
<a href="iraq_pixra2.html">2</a>
<a href="iraq_pixra3.html">3</a>
<a href="iraq_pixra4.html">4</a>
<a href="iraq_pixra5.html">5</a>
<a href="iraq_pixra6.html">6</a>
</div>
The goal is to dynamically change the link style within the nav bar based on the current page being viewed.
Here is my current javascript code where I attempt to find the current page's URL and match it with one of the link tags to set the style:
function setPageBarStyle() {
var pageNavBar = document.getElementById("pagebar");
if (pageNavBar != null) {
var filePath = document.location.pathname;
var fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
var linkTags = pageNavBar.getElementsByTagName("a");
for (var i = 0; i < linkTags.length; i++) {
var url = linkTags[i].href;
var urlLastPart = url.substring(url.lastIndexOf('/') + 1);
if (urlLastPart == fileName) {
linkTags[i].style.border="thin solid blue";
}
}
}
}
setPageBarStyle();
I'm seeking advice on how to enhance the code since I'm new to DOM scripting.
I feel that my method of splitting the path is too verbose with many variables. I suspect using regex might be more efficient, but unsure how to implement it in javascript/DOM.
Your help would be greatly appreciated. Thank you.