I am having trouble accessing the 'split' property in jQuery when trying to add an active header link

Struggling with a jquery issue where I can't seem to read the property 'split' from an active link in the header. I've included my code snippet below for reference, any help figuring out the problem would be greatly appreciated.

Snippet:

$(document).ready(function() {
  var url = $(location).attr('href');
  var parts = url.split("/");
  var last_part = parts[parts.length - 1];
  $("li").each(function() {
    var link = $(this).find("a").attr('href');
    var parts = link.split("/");

    if (last_part == parts[parts.length - 1]) {
      $(this).addClass('active');
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header id="header">
  <nav id="main-menu" class="navbar navbar-default  navbar-fixed-top">
    <div class="container">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                            <span class="sr-only">Toggle navigation</span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
        <a class="navbar-brand" href="/index"><img src="/resources/images/logo.png" alt="logo"></img>
        </a>
        <span class="" style="margin-left:10px;font-weight:bold;text-align:center;margin-top:18px;text-transform:uppercase;cursor:pointer"> </span>
      </div>
      <div class="collapse navbar-collapse navbar-right">
        <ul class="nav navbar-nav" style="text-transform:uppercase; font-size:14px; font-weight:600">
          <li class="scroll"><a href="/views/index.jsp">Home</a></li>
          <li class="scroll"><a href="/views/features.jsp">Features</a></li>
          <li class="scroll"><a href="/views/services.jsp">Services</a></li>
          <li class="scroll"><a href="/views/pricing.jsp">Pricing</a></li>
          <li class="scroll"><a href="/blog/blog?page=1">Blog</a></li>
          <li class="scroll"><a href="/views/contact.jsp">Contact</a></li>
          </a>
          </li>
        </ul>
      </div>
    </div>
    </div>
  </nav>
</header>

Still stuck on what might be causing this issue

Answer №1

If you are utilizing jQuery version 1.6 or higher, the issue may lie in

var url = $(location).attr('href');
var parts = url.split("/");

location is an object with an href property; it is not a DOM element, and it does not have an href attribute. According to the jQuery API documentation:

The distinction between attributes and properties can be crucial in certain situations. Prior to jQuery 1.6, the .attr() method sometimes considered property values when retrieving specific attributes, leading to inconsistent behavior. As of jQuery 1.6, the .prop() method allows for explicit retrieval of property values, while .attr() fetches attributes.

You might consider trying

var parts = location.href.split("/");

or, if you prefer to stick with jQuery,

var parts = $(location).prop("href").split("/");

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

Tips for keeping a label above an input field

Is it possible to add a styled label on top of an input element? I have seen images placed inside input elements for indicating the type of input accepted. For example, in a login form, a user icon represents the username field and a key icon represents th ...

jQuery's ability to load pages seamlessly is unmatched

My website is filled with images, and in order to speed up the loading time, I added a loading screen. Currently, it's a white overlay with the following CSS: #loader{ width: 100%; height: 100%; position: fixed; z-index: 9999999999999 ...

Distinguishing between client side rendering and server side rendering is the backbone of web development

My goal is to give users the option to request webpages from my website either directly from the server or by clicking on links, which will be managed by Backbone's router. When a user requests a webpage directly from the server, they will receive a ...

Equal gutters are present between CSS floats

After conducting various experiments, I have devised a method to incorporate fixed and equal gutters between floats. My approach involves using positive and negative margins as well as multiple wrappers, making the solution somewhat cumbersome. However, I ...

My string is being cut off due to the HTML value

My webpage utilizes HTML5 to enable file uploads directly from the browser. The uploaded file is a PDF that needs to be displayed within an <input type="text"/> The following is my code snippet: var files = evt.target.files; // FileList object // ...

Tips for sending a parameter to jQuery's .fadeOut()

I have a specific object that I would like to apply the .fadeOut() method to. Before delving into that, let's explore how I can pass an object to the .click() method: this.$title.click({item: this}, function (event){ var item = event ...

One of the two buttons on the form must be selected

Within a form, I have implemented two buttons that are structured like this: <button name="option" id="option" value="A" class="btn btn-outline-primary" onclick="storeTime()"> Select Option A </but ...

Evaluating the layout of a webpage with each new code update

I'm currently in search of a testing framework to evaluate the frontend and design aspects of my application. We are developing an Angular application and utilizing Protractor for end-to-end tests, but I am curious about how to test the visual design ...

Supervising the organization of HTML sections for an offline web application

Currently, I am developing an offline HTML5 application that involves a significant amount of DOM manipulation through the creation of HTML strings within JavaScript functions. For example: var html=''; html+='<div class="main">&apos ...

Utilize Antiforgery Protection in ASP.NET Core Alongside JQuery

I am currently using JQuery in conjunction with ASP.NET Core 1.0.1 and implementing the following Ajax call: $("#send-message").on("submit", function (event) { event.preventDefault(); var $form = $(this); $.ajax({ url: "api/messages", dat ...

Is there a way to restrict my input to only 10 numbers without allowing any characters?

Is there a way to restrict the phone number input to only allow 10 numbers and exclude any other characters? Currently, setting the maxLength attribute limits the characters to 10 but allows additional characters as well. If I change the type attribute to ...

Populating table with information stored locally

Hello there, I am currently working on a journal project where I am facing an issue with the getItem function of localStorage. Whenever I add entries to the table and refresh the page, all the entries disappear except for one row with default input values ...

How do I add a logo next to a title using CSS Bootstrap?

I am having trouble using Bootstrap to position my logo alongside my website name. I opted for Bootstrap because I want it to adapt smoothly as the webpage's dimensions change, but I'm struggling to get it right. Since I'm new to Bootstrap, ...

Exploring the syntax for navigating with JS Angular and HTML, such as when using the code snippet: ng-click="save(userForm)"

I am struggling to grasp the functionality of a specific part of this code. Despite my efforts to find tutorials, I have been unable to locate relevant information. There are two lines in particular that puzzle me: <button type="submit" class="btn btn ...

The recently added DOM elements are now able to be manipulated using the each() method

Using AJAX, I load some data into a specific div. However, my each function does not work on the newly added DOM elements. How can I bind it with something like "live" or "on" so that it takes effect on the newly added DOMs via AJAX? $('ul.bigs > ...

How can Vue.js deactivate or activate a dropdown based on a checkbox's state?

My task is to toggle the enabled/disabled state of a dropdown called combo-select when a checkbox is checked. The functionality works as expected when I click on Add Name, but not when I am in Editing Name mode and check the box for No Client. https://i.s ...

Creating an HTML button that will execute JavaScript code when clicked

My goal is to create a button that, when clicked, updates the background of another div. These buttons are dynamically generated using PHP from images in a folder. <!DOCTYPE html> <html> <head> <meta charset="UTF-8> <scr ...

Multiple keyup events being triggered repeatedly

Currently, I am developing an Angular 4 application. Within my component's HTML, there is a textbox where users can input text. As soon as the user starts typing, I want to trigger an API call to retrieve some data. The current issue I am facing is t ...

Where can I find the Semantic UI site variables?

I am working on a Django/Python application and I would like to incorporate semantic UI into my views. To achieve this, I am importing semantic UI using a CDN link in my base HTML file as shown below... <head> ... <link rel="stylesheet" ...

What is the best way to trigger the selection options in a dropdown menu with several buttons?

Is it possible to display the options from a select-option tag using a different button? I have either a div or another button. I want to be able to show the list of options from my select tag by clicking this button. Here is my select tag: <select&g ...