Enhancing my Javascript code by adjusting the styling of a link within the page navigation bar

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.

Answer №1

Here is a better way to achieve the same result:

var aUrlLastPart = linkTags[ii].href.split("/").pop();

Using the Pop() method eliminates the need for extra variables and simplifies the code.

If you want to make JavaScript development easier, consider using libraries like jQuery.

I hope this alternative solution proves helpful! :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm encountering an issue with the React state where it seems to be endlessly nesting

I am new to React and I seem to be encountering an issue where every time I trigger a click event, the state object continues to nest. The code snippet below is part of the App component. const [state, setstate] = useState('') useEffect(() =& ...

Having trouble connecting angular repository data with promise

I have been trying to implement the repository pattern in my Angular application. I can see that the JSON data is successfully retrieved over the network when I call my repository, but I am facing issues with binding it to my view. I have injected the rep ...

Implementing a secure route in Next.js by utilizing a JWT token obtained from a customized backend system

Currently, I am in the process of developing a full-stack application utilizing NestJS for the backend and Next.js for the frontend. Within my NestJS backend, I have implemented stateless authentication using jwt and passport. My next goal is to establis ...

Arrange the objects in the array in React based on their time and date of creation

As a newcomer to the world of React.js and Redux, I am faced with an array of objects structured like this: quizList = [ { createdDate : 1543314832505, id:5bfd1d90d4ed830001f589fc, name:'abc'}, { createdDate : 1543314152180, id:5bfd1ae8d4ed83000 ...

Using Pug/Jade, be sure to call a function during each loop iteration

I'm attempting to develop a basic app, similar to a TO-DO LIST. I want to generate divs dynamically (with incremental ids) when a Button is clicked and then enter some text into an HTML input field. For example: <div id="item1"> <div id="ite ...

Guide on how to add multiple options to a select element in HTML using prototype.js

What is the best way to add multiple options to a select tag in HTML using prototype js? Appreciate your help. ...

Why does the custom method only trigger once with the addEventListener?

I am attempting to connect the "oninput" event of an input range element to a custom method defined in a corresponding typescript file. Here is the HTML element: <input type="range" id='motivation-grade' value="3" min="1" max="5"> This i ...

Transform a numerical variable into a string data type

I am faced with a situation where I have a variable named val which is currently set to the number 5. Now, my goal is to update the value of val so that it becomes a string containing the character "5". Could someone guide me on how to achieve this? ...

hyperlink to choose a specific option from a drop-down menu

The challenge I am currently working on involves page1.html <a href="/foo"></a> foo.html <select ng-model="ctrl.listvalues"> <option id="{{item.value}}" ng-repeat="item" in ctrl.availableValues" value="{{item.value}}">item.di ...

The data type 'void' cannot be assigned to type '(event: MouseEvent<HTMLDivElement, MouseEvent>) => void'

Can you assist me in understanding what has occurred and provide guidance on the necessary steps to resolve it? I am currently working on a website where I am in need of hooks to update the state. The issue seems to be related to the onClick events within ...

Simply click on a single checkbox in ReactJS

Is there a way to implement a method in which clicking on one checkbox will automatically deselect the other checkboxes, allowing only one selection at a time? import React, { Component } from 'react'; export default class Tablerow extends Comp ...

Creating an optimized dashboard in Next.js: Expert tips for securing pages with specific roles, seamlessly implementing JWT authentication without any distracting "flickering" effect

Given our current setup: We have a backend ready to use with JWT authentication and a custom Role-Based Access Control system There are 4 private pages specifically for unauthenticated users (login, signup, forgot password, reset password) Around 25 priva ...

How to manage UNC paths and "mapped network drives" within an Electron application?

I have developed a cross-platform (macOS-Windows) app using Electron that functions smoothly with files and media assets from a local drive. However, it encounters issues when dealing with UNC paths and "mapped network drives". Since I am a contractor, I d ...

Middleware in Expressjs ensures that variables are constantly updated

I'm attempting to accomplish a straightforward task that should be clear in the code below: module.exports = function(req, res, next) { var dop = require('../../config/config').DefaultOptions; console.log(require('../../config/ ...

Vue.js: The chart's dataset has been refreshed

I am utilizing vue-chart.js to create a basic chart. import { Line } from 'vue-chartjs'; export default { extends: Line, mounted() { this.renderChart({ labels: [this.getChartLabels], datasets: [ { label: &a ...

Angular2+ does not return any elements when using .getElementsByClassName() even if they are present

I have a question that seems simple, but I can't seem to find the answer anywhere. I've looked through past questions but still haven't found a solution... In my Angular template, there is a large amount of text inside a div, and some parts ...

Error: Encountered an unexpected token while trying to parse multiple form functions

I recently added the following submission function to my .js file: $( "form" ).on( "submit", function( event ) { event.preventDefault(); var data = $( this ).serialize(); $.ajax({ type: "POST", url: "content/rev/a_sub ...

"Enhancement in Chrome: Inclusion of Origin header in same-origin requests

When we POST an AJAX request to a server running locally, the code looks like this: xhr.open("POST", "http://localhost:9000/context/request"); xhr.addHeader(someCustomHeaders); xhr.send(someData); The webpage where this javascript is executed is also on ...

Is the MVC pattern adhered to by ExpressJS?

Currently, I am diving into the world of creating an MVC Website With ExpressJS using resources from I'm curious to know if ExpressJS strictly adheres to the MVC pattern, or if it follows a different approach like Flask which focuses more on the "C" ...

Summon wicket from the non-wicket-component entity

I am currently utilizing js-lib to transform text into a rich-editor, complete with options such as "bold", "italic" and more. The RichEditor also includes an UploadImage button, for which I am able to modify the call-back function: function startUploadi ...