Creating identical class names for UL elements underneath LI using JavaScript

In my attempt to dynamically generate the class name within the ul element, I successfully achieved the expected result. The outcome can be viewed in the console of the snippet provided for reference.

However, I'm facing a challenge when attempting to create the same class name for the ul elements generated under a li element. For instance, if there is a li element with the class name "a", and multiple ul elements are created under the same li element, the class names of the ul should remain consistent. Instead, the classes are being numbered sequentially.

The desired outcome is as follows:

<li class="a">
    <a href="/">First</a>
    <ul class="main-nav-list">
        <li class="b">
            <a href="/">Type of menu</a>
            <ul class="main-nav-list ul-1">
                <li class="c"><a href="/">Summer</a></li>
            </ul> 
        </li>
        <li class="b">
            <a href="/">Type of menu</a>
            <ul class="main-nav-list ul-1">
                <li class="c"><a href="/">Summer</a></li>
            </ul>
        </li>

I have made an attempt to achieve this dynamic class generation:

var ul = document.querySelectorAll(".main-nav ul");

ul.forEach((each, i) => {
    each.classList.add("ul-" + i);
    console.log(each)
});
<nav class="main-nav">
  
  <ul class="main-nav-list">
    <li class="a">
      <a href="/">First</a>
      
      <ul class="main-nav-list"> 
        <li class="b">
          <a href="/">Type of menu</a>

          <ul class="main-nav-list">
            <li class="c"><a href="/">Summer</a></li>
          </ul>

        </li>
        <li class="b">
          <a href="/">Type of menu</a>

          <ul class="main-nav-list">
            <li class="c"><a href="/">Summer</a></li>
          </ul>

        </li>
      </ul>
    
    </li>
  </ul>

</nav>
https://i.sstatic.net/CPbhJ.png

If the first ul has the class ul-0, then subsequent ul elements should also have ul-0 as their respective classes. Any assistance on this matter would be greatly appreciated!

Answer №1

To apply a specific class to each ul element within every li, you need to iterate through all the li elements and then target their respective child ul elements to add the desired classes.

// Selecting all li elements under the main ul on the page
var lis = document.querySelectorAll(".main-nav>ul>li");

lis.forEach((each) => {

    // Selecting all ul elements inside each li
    let innerUls = each.querySelectorAll(`:scope>ul`);

    // Adding a custom class to each ul element
    innerUls.forEach((itm, index) => {
      itm.classList.add("ul-" + index);
    })
});
<nav class="main-nav">
  
  <ul class="main-nav-list">
    <li class="a">
      <a href="/">First</a>

      <ul class="main-nav-list"> 
        <li class="b">
          <a href="/">Type of menu</a>
          
          <ul class="main-nav-list">// In my case, if the class is ul-1 then next li ul is generating as ul-2 but I want it to be consistent for both li components
            <li class="c"><a href="/">Summer</a></li>
          </ul>

        </li>
        <li class="b">
          <a href="/">Type of menu</a>

          <ul class="main-nav-list">
            <li class="c"><a href="/">Summer</a></li>
          </ul>

        </li>
      </ul>>
    
    </li>
    
    <li class="a">
      <a href="/">Second</a>
      
      <ul class="main-nav-list"> 
        <li class="b">
          <a href="/">Type of menu</a>

          <ul class="main-nav-list">// In my case, if the class is ul-1 then next li ul is generating as ul-2 but I want it to be consistent for both li components
            <li class="c"><a href="/">Summer</a></li>
          </ul>

        </li>
        <li class="b">
          <a href="/">Type of menu</a>

          <ul class="main-nav-list">
            <li class="c"><a href="/">Summer</a></li>
          </ul>

        </li>
      </ul>>;
      ...


UPDATE

To recursively add classes to ul elements:

let classNames = ['a', 'b', 'c', 'd', 'e'];
function addClassToUls(ul, level) {
  var lis = ul.querySelectorAll(':scope>li');
  lis.forEach((each) => {

    // selecting all uls inside each li
    let innerUls = each.querySelectorAll(`:scope>ul`)

    // adding class name to each ul
    innerUls.forEach((itm, index) => {
      itm.classList.add(`ul-${level}-${classNames[index]}`);
      addClassToUls(itm, level+1);
    })
  })
}

let mainUls = document.querySelectorAll(".main-nav>ul");

mainUls.forEach(ul => addClassToUls(ul, 1))
<nav class="main-nav">

  <ul class="main-nav-list">
    <li class="a">
      <a href="/">First</a>

      <ul class="main-nav-list">
        <li class="b">
          <a href="/">Type of menu</a>

          <ul class="main-nav-list">// In my case, if the class is ul-1 then next li ul is generating as ul-2 but I want it to be consistent for both li components
            <li class="c"><a href="/">Summer</a></li>
          </ul>
        ...

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

Unattaching Events in AngularJS

I'm still navigating my way through the realms of Angular and MVC programming, uncertain if I'm on the right track. There's a jQuery snippet that I wish to implement in some of my partials, but not all. With event listeners that persist eve ...

Mars Eclipse, AngularJS and the power of NodeJS

Could you please assist me in understanding the workings of node.js and angular.js within Eclipse? I am using Eclipse Mars and I would like to run my Angularjs project on a local server (localhost:8080) but I am unsure of how to accomplish this. I have a ...

Substituting text in a document by utilizing two separate arrays: one holding the original text to be found and another storing the corresponding text for

I am facing a challenge with replacing specific text strings in a file. I have two arrays - one containing the strings that need to be located and replaced, and the other containing the replacement strings. fs.readFile("./fileName.L5X", "utf8", function( ...

Refreshing the DeckGL HexagonLayer upon changes to the data array/Initiating a reload for the DeckGL HexagonLayer

I am currently using DeckGL along with React to showcase data on an OpenStreetMap. My goal is to incorporate filters to allow for different views of the data I possess. The main issue I encounter is the inability to refresh the layer representing the data ...

Transferring data between JavaScript and PHP

Is there a way to transfer data from JavaScript to PHP when a button is clicked? For instance, can the getdate() function's result be sent to PHP? This transferred value will then be utilized for database manipulation. ...

What is the behavior of a variable when it is assigned an object?

When using the post method, the application retrieves an object from the HTML form as shown below: code : app.post("/foo", (req, res)=> { const data = req.body; const itemId = req.body.id; console.log(data); console.log(itemId); }) ...

A guide on incorporating and utilizing third-party Cordova plugins in Ionic 5

Attempting to implement this plugin in my Ionic 5 application: https://www.npmjs.com/package/cordova-plugin-k-nfc-acr122u I have added the plugin using cordova plugin add cordova-plugin-k-nfc-acr122u but I am unsure of how to use it. The plugin declares: ...

Tips for making a div with a single triangular side using Reactjs

Hey there, I'm looking to design a header similar to the one shown in this image. Can someone provide guidance on how I can achieve this UI using React.js? https://i.sstatic.net/zmW5x.jpg ...

Navigating to the bottom of a specific element by scrolling

I am currently working on enhancing a module within the application I'm developing. The goal is to automatically scroll the browser window to the bottom of an element when said element's height exceeds the height of the window. The functionality ...

A loop that incorporates a jQuery JavaScript dropdown menu along with some calculations

My goal is to have multiple dropdown lists populated from a PHP while loop. Each select dropdown has a corresponding textbox that should update its value when a selection is made. However, the current script only works for a single dropdown outside of the ...

What is the best way to conceal a broken image icon without sacrificing all of the stylesheet?

Can someone assist me in understanding and modifying this code? Here is the code snippet: <table> <tr> <td> <img src="" id="img" class="img" style="width:100%;height:200px;background-color:#ccc;border:2p ...

Unable to choose an input form within a CSS div

Just installed a jQuery responsive menu tab but encountering issues with selecting forms to input values. It seems like a CSS problem that I cannot identify. Please assist me in resolving this issue. Below is the HTML code snippet: <div class="contai ...

Creating a dynamic canvas with a three-dimensional model using three.js: A step-by-step guide

I'm currently developing a website where I have integrated a canvas element to display a 3D object (specifically, a cube) using three.js. The canvas is housed within a div, following the guidelines found in various documentation. The issue arises wh ...

Encountering a React.js issue when attempting to update data

When attempting to update fields with a given drugid, an error occurs. For example, selecting drugid as 1 and clicking the update button results in an error message stating 'localhost:8081/drug/1' not found. In the MongoDB database, there is also ...

Transforming JavaScript Code into C# Syntax

I could really use some assistance. I've got a JavaScript code snippet here. var regiondb = new Object() regiondb["africa"] = [{value:"1", text:"Cairo"}, {value:"2", text:"Casablanka"}, {value:"3", text:"T ...

Is it possible to customize the formatting of the information displayed within a details tag when it is nested under a summary

Is there a way to format the details information so that it aligns underneath the summary tag? Currently, both lines of text are aligned to the left. <details> <summary> Summary 1 </summary> Details 1 </details> ...

The positioning of sub-menu items is incorrect

I would like the subitems in the menu to be positioned directly under the main menu items instead of being slightly offset to the right. CSS ul#menu { float:left; width:100%; margin:0; padding:0; list-style-type:none; background-c ...

Is it possible to design a Controller and View that can manage the creation of one-to-many objects, specifically a single "container" object along with an unlimited number of "content"

One of the functionalities for users on the website will be the ability to create documents made up of chapters in a one-to-many relationship. Traditionally, this would involve creating separate views for chapter and document creation. How can I develop ...

I am attempting to integrate the file path of my images using PHP

Let me start off by showing you the file structure of my website. File Structure Of my website In order to organize my code, I created a header file named header.html.php which contains all the necessary elements for the header, including an image tag fo ...

Error message: Next.js - Unable to access properties of an undefined object (user)

I am currently utilizing Next.js and Next-auth in my current project. Within this project, I am working on creating a Sidebar component that will display a list of items specific to each user. To achieve this, I am using the useSession hook to retrieve t ...