Is there a way to efficiently update the CSS class attribute for all list items using just pure JavaScript?

I am looking to use pure Javascript, not jQuery, to access all elements within a <ul> list and remove the active class from every item except for the one selected in my menu.

Shown below is the list:

<ul id='flash-menu'>
<li id="menu1" class='something active'>item 1</li>
<li id="menu2" class='somethingelse'>item 2</li>
<li id="menu3" class='somethingelse'>item 3</li>
</ul>

This code snippet contains my JavaScript functionality:

if (x < y){
var listItems = document.getElementById('flash-menu').childNodes; 
for (var i=0 ; i<list_items.length ; i++){
        list_items[i].className = list_items[i].className.replace('/\bactive\b/','');
    }
document.getElementById(view_name).className += " active";
}

The last line of this script successfully adds the active class, but I suspect there may be an issue with how I'm targeting and removing classes from other items. Any helpful suggestions would be greatly appreciated! Thank you!

Answer №1

Initially, your regular expression is incorrect:

list_items[i].className.replace(/\bactive\b/, '');

Remember: Avoid using quotes in JavaScript regex. A modified version that works can be found on JsFiddle.


Additionally, I encountered some instances of HTMLTextElements within list_items. These elements are causing issues (Fx3.6/Win7) as they lack the className attribute. To overcome this, you can either:

var list_items = document.getElementById('flash-menu').getElementsByTagName('li');
// Selecting all descendant <li> elements

or by verifying the existence of .className before accessing it in the loop body (example). The latter option is preferable as it only affects direct children (there may be multiple levels of <ul>s within each <li>).


For example,

function updateMenu(view_name) {
    var list_items = document.getElementById('flash-menu').childNodes; 
    for (var i=0, j=list_items.length; i<j; i++){
        var elm = list_items[i];
        if (elm.className) {
            elm.className = elm.className.replace(/\bactive\b/, '');
        }
    }
    document.getElementById(view_name).className += ' active';
}

Answer №2

To retrieve all list items using JavaScript, you can utilize the getElementsByTagName method:

var listitems = document.getElementsByTagName("li");

This function will return an array containing all the list elements, allowing you to iterate through each item and perform any necessary processing.

Answer №3

If you are dealing with multiple ul elements, the first step is to gather all references to them and then handle each ul individually:

var uls = document.getElementsByTagName("ul");

    for (uli=0;uli<uls.length;uli++) {

        ul = uls[uli];

        if (ul.nodeName == "UL" && ul.className == "classname") {

            processUL(ul);

        }

    }

An example of how the processUL function could look like:

function processUL(ul) {

    if (!ul.childNodes || ul.childNodes.length == 0) return;

    // Loop through LIs

    for (var itemi=0;itemi<ul.childNodes.length;itemi++) {

        var item = ul.childNodes[itemi];

        if (item.nodeName == "LI") {

            // Iterate over items in this LI
 insert your code here 
              .....
        }

    }

}

Additionally, you can also utilize: item.className = "classname"; if there is no need to iterate through the children of LI

Answer №4

When using the code <code>document.getElementById('flash-menu').childNodes
, keep in mind that it will also capture white space nodes along with other child nodes.

To update the menu based on a specified view name, you can use the following function:

function updateMenu(view_name) {

    var list_items = document.getElementById('flash-menu').getElementsByTagName('li'), i; 

    for (i=0 ; i<list_items.length ; i++){
            if (list_items[i].className.indexOf('active') > -1) {
              list_items[i].className = list_items[i].className.replace(/\bactive\b/,'');
            }
        }
    document.getElementById(view_name).className += " active";
}

Answer №5

I wholeheartedly concur with jensgram, and I recommend coding in the following manner:

list_items[i].className.replace(/\bactive\b/g, '');

Make sure to include the 'g' modifier in the regex string.

Answer №6

g stands for Global, using ‘/g’ can replace all instances that match the regex. However, if you don't use '/g', only the first instance will be replaced. For example:

var test= "testeetest" ;
alert(test.replace(/e/,"")) ;//result : tsteetest but by using 'g' var test= "testeetest" ;
alert(test.replace(/e/g,"")) ;//result : tsttst

Answer №8

Here is my humble solution that may not be the most efficient, but it gets the job done for me.

document.addEventListener('DOMContentLoaded', initializeEvents);

function initializeEvents() {
    var menuItems = document.querySelectorAll('nav li');

    for (var i = 0; i < menuItems.length; i++) {
        menuItems[i].addEventListener('mousedown', handleMenuClick);
    }
}

function handleMenuClick() {
    var menuItems = document.querySelectorAll('nav li');
    
    for (var i = 0; i < menuItems.length; i++) {
        menuItems[i].classList.remove('active');
    }

    this.classList.add('active');
}

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

Ways to increase the spacing between content boxes using Bootstrap

I currently have a row of three Bootstrap boxes structured like this: <div class="row"> <div class="col-lg-4 pathBoxMain"> <h2>Content</h2> </div> <div class="col-lg-4 pathBoxMain"> <h2>Content</h2> </di ...

Obtaining a cloned HTML object using jQuery in C# the correct way

In my webpage, there is a div with various input elements inside. I want to duplicate the entire HTML content of this div so that I can store it in my database. When I retrieve this cloned HTML in the future, I want it to appear on another page exactly as ...

Repairing a CSS file for Internet Explorer versions 7, 8, and 9

Does anyone have experience with troubleshooting HTML5 CSS3 layouts across different browsers? I recently created a website layout from scratch that looks perfect in Firefox 5, Safari 5.1 and Chrome 12 on Mac. However, when using tools like Adobe BrowserL ...

Should I include container-fluid in the body or main level for a Bootstrap 4 website?

When designing a Bootstrap 4 site, is it better to add container-fluid at the body or main level? For example: <html> <head></head> <body class= "container-fluid"> <header></header> <main></main> <footer ...

AngularJS xeditable: sending updated data to the server

I am currently utilizing AngularJS to display products in a table for my users. Users have the ability to filter the table using categories or keywords. However, they should also be able to edit the product information within the table, such as product nam ...

What is the process for generating an auto-incrementing button with a *different input field*?

After searching everywhere for a code snippet to add another input bootstrap input group, I finally decided to take matters into my own hands and create one from scratch. And would you believe it worked like a charm! ...

What alternative can be used for jquery isotope when JavaScript is not enabled?

Is there a backup plan for jQuery isotope if JavaScript isn't working? For instance, if I'm using the fitColumns feature, is there an alternative layout style available in case JavaScript is disabled, similar to what is seen on the new Myspace? ...

Mobile phone web development using HTML5

I am currently facing an issue with playing sound on mobile browsers. In my code snippet, I have the following: Response.Write("<embed height='0' width='0' src='Ses.wav' />"); While this works perfectly fine on desktop ...

Anticipated a JavaScript module script, but the server returned a MIME type of text/html as well as text/css. No frameworks used, just pure JavaScript

I have been attempting to implement the color-calendar plugin by following their tutorial closely. I have replicated the code from both the DEMO and documentation, shown below: // js/calendar.js import Calendar from '../node_modules/color-calendar&ap ...

Issue with Vue Router failing to navigate to the correct hash location

After clicking a link on the app, I noticed that the Router does scroll to the correct hash location, but it always seems to be one element too high on the page. This issue occurs even though the scrolling functionality is working fine. For instance, if my ...

Angular’s ng-repeat function is behaving erratically as objects are displayed in the console

Having trouble with my ng-repeat not displaying content. Here is the code for my app.js, client controller, factory, and server controller. Everything else seems to be working fine. I can see all the console logs in Chrome and terminal, but the ng-repeat ...

Unable to Load CSS File with Path in ClojureScript Project

Currently, I am working on a project in Electric Clojure that requires importing a CSS file to enhance the styling of my application. While I have been able to add styles using dom/element, the resulting code appears cluttered. What is the most effective m ...

Incorporate Monaco Editor into an AngularJS 1.X project

Due to the challenges presented in this particular issue, I am seeking an alternative JavaScript-based source code editor compatible with AngularJS 1.X. My current exploration has led me to consider utilizing Monaco Editor. While I have successfully execu ...

Ways to extract information from a table cell located next to a table cell with colspan

As a beginner in web scraping, I am gradually making progress. However, I'm facing a tough challenge with this particular task. My goal is to extract data from the ESPN NBA boxscore website: I aim to scrape the names of players labeled as "DNP" (Did ...

"Enhancing Error Handling in Express with Node.js Middleware for Parsing

I've been working on developing a middleware to manage errors, but I'm struggling to send the correct format to my frontend. Below, I'll outline my various attempts in the hopes of getting some guidance on this issue. Attempt 1 app.use(fun ...

Empty HTML fieldset

For a blog article I'm working on, I'd like to include a "Note" box that resembles a <fieldset> with a <legend> <fieldset> <legend>Note</legend> Please take note of this. </fieldset> (check out http:/ ...

New ways to style Links in NextJs 13

I am relatively new to Next.js and I am attempting to create a menu with a hover effect using the following code: import Link from 'next/link'; const MenuItem = ({ href, label }) => ( <Link href={href} className="menu-item"> ...

What is the best way to insert a permanent script tag into the body of a Gatsby site? Can conditional rendering be used to control

As an illustration: - const nation = "USA" import chat from './utils/script'; // script is imported from a file if(nation === "USA") // utilized conditionally in the component { chat } else { console.log("Not USA") } inform me witho ...

Issue encountered - Attempting to provide an object as input parameter to puppeteer function was unsuccessful

Encountering an error when attempting to pass a simple object into an asynchronous function that utilizes puppeteer. The specific error message is: (node:4000) UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: userInfo is not def ...

Utilizing HTML5 to Access and Update custom data attributes

I have implemented the following code: var activeFilter = $('<li></li>').data('input-id', 'mycustomId'); $('#container').append(activeFilter); Now, I am faced with the challenge of retrieving a specific ...