Modify the current link's <li> class

I am facing an issue with the code below which is supposed to change the class of li based on whether the browser URL matches the href attribute within that li.

The current problem I am encountering is that the code changes the class for all li elements, instead of just the ones containing the specific URL.

JavaScript :

$(document).ready(function() {
  $("#subnav a").each(function() {
    if ($(this).attr('href') == document.URL) {
      $('li').addClass("selected");
    }
  });
});

HTML:

<div id="subnav">
  <ul class="tabrow">
    <li><a href="<?php echo $this->config->base_url()?>rankings/all"> Players</a>
    </li>
    <li><a href="<?php echo $this->config->base_url()?>rankings/top-guilds"> Guilds</a>
    </li>
    <li><a href="<?php echo $this->config->base_url()?>rankings/top-masterlevel">Master Level</a>
    </li>
    <li><a href="<?php echo $this->config->base_url()?>rankings/top-voters">Voters</a>
    </li>
    <li><a href="<?php echo $this->config->base_url()?>rankings/top-online">Online</a>
    </li>
  </ul>
</div>

Solution in case anyone needs it. Credits to nem035

$(document).ready(function() {
  $("#subnav a").each(function() {
    if ($(this).attr('href') == document.URL) {
      $(this).parent().addClass("selected");
    }
  });
});

Answer №1

The issue arises from the usage of the selector $('li'), which selects all <li> elements instead of just the parent element of the current <a> whose URL is being compared.

To address this, consider implementing the following approach:

if($(this).attr('href') == document.URL){
  $(this).parent().addClass("selected");
}

Answer №2

PHP Code Inserted:

<?php
$link = $this->config->base_url.'rankings/all';
if($_SERVER['REQUEST_URI'] !== $link) {
    echo('class="selected"');
}
?>

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

To toggle between two scope variables within a view when one is not defined

In my application, I am utilizing two scope variables: $scope.banner and $scope.defaultBanner. The banner is fetched using a service, but in cases where the banner file does not exist, the variable will be empty as the service returns nothing. My goal is ...

The issue of elements flickering while being hidden and shown with jQuery has been observed in both Chrome and

Having trouble with a simple animation using jQuery? While it may work smoothly in Firefox, you might be experiencing flickering in Chrome and Edge. Check out this jsfiddle for reference: HTML <div id="boxes-wrapper"> <div class="box"></ ...

"Utilizing Bootstrap's Table Features within the Moodle Platform

Hey there! I'm currently in the process of updating a client's Moodle website. Our goal is to create responsive tables on the homepage, but I've encountered some challenges. Due to conflicts with other Moodle libraries, I wasn't able to ...

Prevent iPhone from automatically changing phone numbers to grey text color

For some reason, the iPhone keeps changing the phone numbers on my site to grey, despite using Drupal 7. I've heard that this is because the iPhone wants to make them stand out for users to interact with. I tried adding the following code to the head ...

What can I do to prevent my HTML/CSS/jQuery menu text from shifting when the submenu is opened?

After encountering numerous inquiries regarding the creation of disappearing and reappearing menus, I successfully devised a solution that functions seamlessly on desktop and tablet devices. My approach involved utilizing the jQuery .toggleClass function w ...

What could be causing the fluctuation in the length property of my array-like object?

Currently, I am following a JavaScript tutorial that covers the call and apply methods. One thing that has me puzzled is the behavior of an 'array-like object' used in one of the examples: var arrayLikeObj = { 0: 'Marty', 1: 78 ...

Should Errors be Handled in the Service Layer or the Controller in the MVC Model?

Currently, I am in the process of developing a Backend using Express and following the MVC Model. However, I am uncertain about where to handle errors effectively. I have integrated express-async-errors and http-errors, allowing me to throw Errors anywher ...

Eliminate unnecessary words from the sentence

I wrote a sentence but it got split at every space. The data is displayed like this: const escapeRE = new RegExp(/([/\?""])/g); const myDatas = data.map(des => des.Sentence.toLowerCase().replace(escapeRE, '').split(' ')); [ [ ...

You were supposed to provide 2 arguments, but you only gave 1.ts(2554)

Hey everyone, I hope you're having a good morning. Apologies for the inconvenience, I've been practicing to improve my skills and encountered an issue while working on a login feature. I'm trying to connect it to an API but facing a strange ...

The second parameter of the Ajax request is not defined

Having an issue with my Ajax request in Vue.js where the second parameter is logging as undefined in the console. I've been trying to fix this problem but haven't found a solution yet. This is the code snippet for $.ajax(): //$.ajax() to add ag ...

What is the best way to connect to a JSON key that is consistently returned with a varying or unpredictable name?

I am currently working on an Angular 4.x application where my goal is to showcase a random Wikipedia article. Each time I check the JSON data in Chrome Dev Tools under query/pages, I notice that the pageID always has a different number. The structure of th ...

Looking for a reliable tool to check your CSS classes and tidy up your code effectively?

It seems like a common issue with a straightforward solution. I have numerous CSS selectors scattered across various files, many of which may be unnecessary and a directory full of HTML files. My goal is to identify all redundant selectors in my CSS within ...

Bypass Security Check in Firefox

I am facing issues while trying to automate selenium on a website owned by a third party. When an authentication prompt like this appears in Firefox, Selenium fails: https://i.sstatic.net/VHQB4.png You can see a similar situation when clicking the Displ ...

Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maint ...

Can a link be generated that swaps out the original URL redirect for the following visitor upon clicking?

Can the program be fed with a list of links to automatically redirect to the next URL once clicked? In this setup, each visitor would only see one link and not have access to any other URLs in the chain. Is there a way to make this happen? Any suggestion ...

React's router activeClassName feature fails to apply the active class to child routes

<ul className="right hide-on-med-and-down"> <li><IndexLink to="/" activeClassName="active">ABOUT</IndexLink></li> <li><Link to="blog" activeClassName="active">BLOG</Link></li> <li><Link t ...

Unresponsive JavaScript on specific element IDs

I'm experimenting with making three lines perform different animations: line 1 rotating 45deg and translating, line 2 becoming opaque, and line 3 rotating -45deg and translating. Check out my JS Fiddle here <a href="#"><div id="menu" onclic ...

Using Angular.js to fetch information from a MySQL database

I'm currently trying to retrieve data from a MySQL database in an Angular.js application. I have gone through multiple tutorials, but unfortunately, none of them have been successful for me. I have a PHP script that returns a JSON array with example ...

Loop through the array while handling a promise internally and ensure completion before proceeding

I am currently working on populating a response array with Firestore snapshots and creating download links for stored files within each snapshot. Despite trying various solutions involving Promises, the response array consistently ended up being null. do ...

Iterating through the outcome of JSONResponse() from Django using jQuery

I am trying to retrieve the results of an insert operation from my views.py file in JSON format. The view I have looks like this: added={} if request.method=='POST': #Post method initiated. try: for id in allergies: ...