Discovering the element's class within an each loop

I am currently working on a dynamic menu system that changes the style of the active page item in the menu. My approach involves utilizing separate body classes for each page and then iterating through the li elements in the menu to find a match with the body class. Once a match is found, I intend to apply new styling to that specific menu item.

Below is the code I have developed so far:

HTML

<body class="home-state">
...

<div class="menu-left">     
  <ul>
    <li class="home-state">
        <a href="/">Home</a>
    </li>
    <li class="work-state">
        <a href="/work">Work</a>
    </li>
    <li class="services-state">
        <a href="/services">Services</a>
    </li>
    <li class="about-state">
        <a href="/about">About</a>
    </li>
    <li class="blog-state">
        <a href="//blog.example.com" target="_blank">Blog</a>
    </li>
    <li class="shop-state">
        <a href="/shop">Shop</a>
    </li>
    <li class="contact-state">
        <a data-toggle="modal" href="#modal-coworking">Contact</a>
    </li>
    <li class="project-state">
        <a href="/brief/index">Project brief</a>
    </li>
  </ul>
</div>

...
</body>

JS

var bodyClass = $("body").attr('class');

$('.menu-left ul li').each(function(){

First: In this section, my aim is to identify the element's class using $(this).attr("class");, but I encountered some issues

    var element = $(this); 

Second: I plan to implement an if statement to validate whether the class matches the bodyClass

    console.log(element);

Last: Upon finding a match, I will assign the class .active to the respective li element.

});

Answer №1

If you want elements to have multiple classes, consider using a data- attribute instead of a class in the body element to indicate the current page:

<body data-current="home-state">

With this setup, adding the active class to the correct menu item becomes straightforward:

$("li." + $("body").attr("data-current")).addClass("active")

You don't have to iterate over menu items and compare classes like mentioned in the question. Instead, you can directly select the required li element based on its class.

If the body element does not have a data-current attribute, $("body").attr("data-current") will return undefined. This would lead the code to try selecting an element with $("li.undefined") and adding a class, which may be harmless if no such class exists. However, if you wish to explicitly check for the presence of the data-current attribute:

var current = $("body").attr("data-current")
if (current) {
  $("li." + current).addClass("active")
}

Answer №2

There are a few different ways to accomplish this task, but here is a straightforward method:

var currentBodyClass = $("body").attr('class');

$("li." + currentBodyClass).addClass("active");

Alternatively, you can utilize a loop to achieve the same result:

var currentBodyClass = $("body").attr('class');

$(".menu-left li").each(function(index, element) {
    if (currentBodyClass === $(this).attr("class")) {
        $(this).addClass("active");
    }
});

Both of these approaches will work effectively.

Answer №4

You forgot to attach the click event to the menu item. Here is an example of how to do it:

var bodyClass = $("body").attr('class');
$('.menu-left ul li').on( "click", function() {
var myClass = $(this).attr("class");
   alert(myClass);
});

Tested and working: https://codepen.io/anon/pen/XzYjGY

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

Having trouble establishing a connection between node.js and MongoDB

I've been struggling to connect node.js to mongoDb. Despite trying various solutions like changing the URL from localhost to 127.0.0.1 and downloading different versions of mongo (v6, v5, v4 - the current one), I'm stuck. Interestingly, when I ac ...

continuously refresh choices available for selection

I am looking for a way to dynamically populate the second select option based on the selection made in the first select option. While I know how to achieve this using traditional jQuery and HTML, I was wondering if there is a way to update options_for_sele ...

Exploring the Process of Setting Up a Temporary Endpoint in Express

Currently, I am working with the node.js framework express and my goal is to establish a temporary endpoint. This can either be one that automatically deletes itself after being visited once, or one that I can manually remove later on. Any assistance wou ...

Unable to specifically identify or focus on this offspring

I am attempting to target the class has-translucent-status-bar nested within another class called platform-ios To achieve this, I have used the following code: .platform-ios > .has-translucent-status-bar Unfortunately, this approach has not been succ ...

How to extract data-bound value from a <span> element using Angular

I have a table that serves as a form, with most of the cells containing input fields. <td><input id="testingInput2" type="number" placeholder="0"step="1" ng-model="addResources.one"> </td> <td><input id="testingInput2" type=" ...

Can you explain the reference point used in the `drawImage()` function on a canvas?

Here is an inquiry concerning the usage of the drawImage() function. var x = (i-j)*(img[0].height/2) + (ctx.canvas.width/2)-(img[0].width/2); var y = (i+j)*(img[0].height/4); abposx = x + offset_x; abposy = y + offset_y; ctx.drawImage ...

Tips for Uploading the Contents from 2 Select Boxes

In my ASP.NET MVC application, I have two list boxes named #AvailableItems and #AssignedItems. I am able to transfer items from one box to the other. Additionally, there are related values stored as attributes on the Save link that also need to be submitt ...

Sending a null variable via an AJAX post request from jQuery to PHP

Query: <table> <tr> <td id="percentage">Percent:&nbsp; <?php echo $percent; ?> %</td> </tr> </table> <div class="box-footer" style="float: right"> <a href="<?php echo base_url(); ?>stu ...

Error: PageMethods function not recognized on ASPX page

As I review some older code, I can only assume that it worked at some point in time. MyPage.aspx: function GetCompanyList(officeId) { var companyList = document.getElementById('<%= CompanyDropDown.ClientID %>'); if (companyList.le ...

How come my search query in the input form is unable to locate a user in the table?

I am currently facing an issue with my PHP search functionality. I have a table called "users" and I want to find the user that matches the name inputted by the user and display it on the screen. However, for some reason, the program is not displaying the ...

Footer div is being covered by the page

I am currently working on a website built with "WordPress", and I have implemented a mobile footer plugin that is designed to only appear on mobile devices. However, I am encountering an issue where the page content overlaps the footer on phones. I attemp ...

Is it possible to scroll the grid horizontally?

I have a grid that scrolls vertically, with columns adjusting their width automatically. .grid { display: grid; overflow-y: auto; grid-template-columns: repeat(auto-fit, minmax($min-column-width, 1fr)); } Now, I'm attempting to create a horizon ...

The process of including a property in Vue.JS

Looking to include this property on my button: uk-toggle="target: #id" The desired outcome is: <button uk-toggle="target: #id" type="button">Click</button> I'm trying to achieve this with Vue.JS but I'm facing some difficulties. H ...

Update the display of the mouse pointer

I use CSS to set a custom cursor image: #scroll_up{ display: block; position: absolute; width: 960px; height: 300px; cursor: url(../imgs/cursor_up.png), auto; } The above style is assigned to a div element so that the cursor appea ...

What is the best way to automatically create a line break once the User Input reaches the end of a Textbox?

I've been searching for a solution to this question without any luck. Here is the tag I'm working with: <input type="text" id="userText" class="userTextBox"> And here is my CSS: .userTextBox { /* Add marg ...

When working with angular.js and angular-sanitize.js, the src attribute is removed from JSON HTML data

I'm new to Angular and I'm really enjoying learning how to work with it. Currently, I have a simple JSON file that contains text structured like this: "gettingstarted":{ "title":"Getting Started", "content":"<img ng-src='i ...

The next button will only activate once all input forms have been completed in multiple forms

In the JavaScript code: var current_fs, next_fs, previous_fs; //fieldsets var left, opacity, scale; //fieldset properties that will be animated var animating; //flag to prevent rapid glitches from multi-clicking $(".next").click(function(){ if(animati ...

Substitute the information in the table with new data

I am working with an HTML table that has 5 columns, one of which contains dates. I need to convert the date format only if the data is not empty. To achieve this, I am utilizing moment.js for date formatting. While the date format conversion works perfect ...

Error in Heroku deployment - Express and React app displaying a white screen

I am encountering a challenging situation as I attempt to understand the issue at hand. Following the deployment of my React/Express application on Heroku, the build and deployment proceed without errors, but the React frontend appears blank. The browser ...

"What are some strategies for locating a specific item within a MongoDB database, or perhaps querying for all

I am currently searching for a specific item using the following code: Product.find({ category: "bracelet" }); In one scenario, I need to find items with any category value or simply search for all items like this: let cat; if (req.body.cat) ...