Guide to creating a nested list using the jQuery :header selector

Here is the structure of my html:

<h1 id="header1">H1</h1>
  <p>Lorem ipsum</p>
    <h2 id="header2">H2</h2>
      <p>lorem ipsum</p>
    <h2 id="header3">H2</h2>
      <p>lorem upsum</p>
       <h3 id="subHeader1">H3</h3>
       <p>Lorem Ipsum</p>

To retrieve all headings with an ID, I am using this jQuery selector:

var headings = $( ":header[id]" );

My goal is to create a nested list of all these headings in this format:

<ul><li>H1
     <ul><li>H2<li>
         <li>H2
           <ul><li>H3</li></ul>
         </li>
      </ul>
 </li></ul>

I have been struggling to achieve this and couldn't find a solution on Stack Overflow. While I can create a flat list, building a nested one has proven to be more challenging.

If anyone could offer assistance or guidance, I would greatly appreciate it. Thank you!

Answer №1

Mastering this technique requires a combination of algorithmic knowledge and familiarity with jQuery. It's not as simple as just implementing an algorithm; understanding how to use jQuery properly is crucial in coding it effectively.

The approach involves initializing a root ul, storing references to child headers within each ul, then iterating through this collection to convert each header into a nested ul. These newly created ul elements are added to a stack-like structure, which is processed in a while loop until the stack is empty.

Explaining this process can be challenging, especially for beginners new to algorithms and jQuery. Below is the code snippet demonstrating this technique:

// Initialize the root UL
var ul = $('<ul>');
for(var i = 1; i < 8; i++){
  var hs = $('h' + i);
  if(hs.length){
    ul[0].childHeaders = hs
    ul[0].childHeaderLevel = i;
    break;
  }
}

var rootUl = ul;

// Main loop
while(ul.length){    
  var nextUl = $();
  
  // Loop through each ul
  ul.each(function(){
     var innerUl = this;
     var n = this.childHeaderLevel;
     
     // Convert each childHeader into a ul
     innerUl.childHeaders.each(function(i,elem){
        var childUl = $('<ul>').append('<li>' + $(elem).html() + '</li>')
                               .appendTo(innerUl);
                               
        childUl[0].childHeaders = $(this).nextUntil('h' + n)
                                         .filter('h' + (n+1));
        childUl[0].childHeaderLevel = n + 1;            
        nextUl = nextUl.add(childUl);
     });                            
  });
  
  ul = nextUl;   
}

// Append the root UL to the body after emptying it
$('body').empty().append(rootUl);

See Demo Here.

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

The function .play() cannot be executed on document.getElementById(...) - it is not a

There is an error in the console indicating that document.getElementById(...).play is not a valid function. import React from 'react'; const musicComponent=(props)=>{ const style={background:props.color} return( <div classN ...

What should I do to resolve the issue of ajax failing to update data randomly?

This script is designed to take the value entered into an HTML form and send it to the ../Resources/BugReport.php file. The data is then inserted into a database in that file, and the table in the ../Resources/BugDisplay.php file displays the information f ...

Guideline on extracting private keys from Windows Certificate Manager

I am currently working in a Windows environment setting. Within my organization, we act as our own certificate authority for internally-used https applications. I have obtained a certificate from our system for a private web server I created. While using ...

Repeated calls to Angular's <img [src]="getImg()"> frequently occur

Can someone help me figure out what's going on here? Recently, I set up a new Angular project and in app.component.html, I have the following code: <img [src]="getDemoImg()"> In app.component.ts: getDemoImg(){ console.log('why so m ...

What is the best way to accomplish this task with ajax?

Hello, I'm new to using ajax and jquery. Could someone please explain how I can achieve this without page refresh? Here is my PHP code: <div class="recentwork"> <div class="imgholderfloat"> <?php include 'process/connect.php' ...

The function Router.use is looking for a middleware function, but instead received an object in node.js /

I encountered an issue while trying to setup routing in my application. Whenever I attempt to initialize a route using app.use() from my routes directory, I receive an error stating that Router.use() requires a middleware function but received an Object in ...

modifying the appearance of the play button through a JavaScript event without directly altering it

I am currently working on building a music player from scratch using HTML, CSS, and JavaScript only. To store the list of songs, I have created an array named "songs" with details such as song name, file path, and cover image path. let songs = [ {songNa ...

Customize the toggle icon for the accordion in Framework7

I took inspiration from the custom accordion elements provided in the documentation and made some alterations to the icons. However, I'm facing an issue with getting the toggle functionality of the icons to work properly. My goal is to have a "+" dis ...

The postMessage function in my Javascript SlackBot seems to be flooding the channel with messages

I am currently setting up a Slack bot using JavaScript combined with several useful libraries. The main function of this bot is to execute a postMessageToChannel method whenever a user in the channel mentions the specific keyword "help." However, I am fa ...

Encountering the error "Error: Maximum update depth exceeded" while coding a React private Route with infinite

Attempting to render components inside private routes only if the user is authenticated, but encountering an error message that reads: "Error: Maximum update depth exceeded." This issue typically arises when a component continuously calls setState within c ...

How to Send Data to ASP.NET MVC Controller Using AJAX Request with jQuery

I am trying to send parameters to a controller from jQuery, but I am struggling with it. The call works fine without parameters when the URL is just /SurveySection/EditLocalization. Shouldn't it be something like this: /SurveySection/EditLocalization? ...

When trying to upload a file through input using WebDriver, the process gets stuck once the sendKeys

WebElement uploadInput = browser.findElementByXPath("[correct_identifier]"); uploadInput.sendKeys(elementPath); The script successfully initiates the file upload process, however, the custom JavaScript loading screen persists and fails to disappear as exp ...

Possible issue with accurate indexing causing caption error with API images in React

Continuing from: Implementing a lightbox feature in react-multi-carousel for my ReactJS app My application utilizes react-images for the lightbox functionality and react-carousel-images for the carousel. The API provides a title and image data. The issue ...

How to include a javascript file in a different file and compile it using Node.js

For running my practice JS files, I rely on Node. As an example, I use node bts.js. In order to implement a queue, I decided to install Collections by using the command npm install collections --save. You can also see this reflected in the hierarchy shown ...

populate vueJS table with data

I encountered an issue while trying to load data from the database into my table created in VueJS. I have set up my component table and my script in app.js, but I am seeing the following error in the view: [Vue warn]: Property or method "datosUsuario" ...

Modify the website address and show the dynamic content using AJAX

$(function(){ $("a[rel='tab']").click(function(e){ //capture the URL of the link clicked pageurl = $(this).attr('href'); $("#Content").fadeOut(800); setTimeout(function(){ $.ajax({url:pageurl+'?rel=tab&apo ...

Creating a Custom Form Control in Angular 2 and Implementing Disable Feature

I have developed a unique custom control using ControlValueAccessor that combines an input[type=text] with a datepicker. While the template-driven forms accept it without any issues, the situation changes when implementing the model-driven approach (react ...

What is the best way to query the ng-model table using xpath in Selenium with Java?

I'm having trouble finding a table from DOCTYPE Html using xpath or className in Selenium/java. I can't seem to locate the locator. How can I retrieve the table using selenium java? Neither of the following paths are effective. You can view a sc ...

When modifying a string in React, the edit always somehow ends up at the very tail end

In my ReactJS app, I have a Material-UI input element. Everything is working well except for one issue - when I try to edit the text in the middle of the string, the cursor always jumps to the end of the string after every letter I input. I suspect this m ...

I am attempting to modify the text of a specific button in jQuery using HTML, but I am encountering difficulties in making

I am having trouble updating the text of a specific button in HTML using jQuery. Here is my jQuery code: <script> $(document).on('click','.track',function() { var track_button_id = $(this).attr("id"); $.ajax({ ...