Showing a multi-column layout for an HTML ul list

I have an automatic nested list structure that looks like this

<ul>
  <li>AAA</li>
  <li>BBB
    <ul>
      <li>111
        <ul>
          <li>XXX</li>
        </ul>
      </li>
      <li>222</li>
    </ul>
  </li>
  <li>CCC</li>
  ...etc...
</ul>

I am looking to arrange the content in columns as shown below:

AAA    111    XXX
BBB    222
CCC

By using JQuery and some CSS techniques, I can easily create a navigation menu. For example, selecting BBB from the first column will display its children in the second column while hiding any other second-level ULs.

My challenge lies in styling the list to achieve the desired column layout for different depths. Adding tags to each UL or LI to indicate depth is one option. However, when attempting to use relative positioning to shift each column left, vertical gaps are created where entries were moved. Absolute positioning solves this issue but may not be the most elegant solution. Any suggestions for a better approach?

Answer №1

By utilizing recursive functions, this task becomes relatively straightforward: http://example.com/recursive-function-example.

For a more interactive approach, consider storing the parent-child relationships of elements and displaying the relevant ones upon user interaction.

var $row = $("#row");

function extractText(node) { // retrieves text content excluding children
    return node.clone()
            .children()
            .remove()
            .end()
            .text();
}

function processElement(element, level) {
    element.children().each(function() { // iterate through children
        var $child = $(this);
        var targetCell = $row.find("td").eq(level); // locate cell to append this level to
        var appendedContent = extractText($child) + "<br>"; // content to append
        if(targetCell.length) { // check if cell exists
            targetCell.append(appendedContent);
        } else { // create new cell if it doesn't exist
            $row.append($("<td>").append(appendedContent));
        }
        var children = $child.children();
        if(children.length) { // recursively call for children, if any
            processElement(children, level + 1);
        }
    });
}

processElement($("ul:eq(0)"), 0); // initiate the process

Further reading: http://example.com/jquery-text-without-children

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

"Capturing the essence of your online presence: The

I recently completed a website for my Students Organization, which includes a special page dedicated to recognizing the individuals who helped organize our activities. Each member is represented with a photo on this page, sourced from their Facebook profil ...

In the thymeleaf fragment, the th:field attribute is marked with a crimson underline

I am facing an issue with a fragment that opens a modal when a button is clicked. Inside the modal, there is a form with a text field for token and submit button. However, I am getting a red squiggle underneath the th:field attribute "token", and I'm ...

Ways to enhance the appearance of the parent element when the radio button is clicked

Hey there! So, I have a situation where I'm working with two radio buttons and I want to apply certain CSS styles to the parent box (<div>) when a radio button is selected (checked). Here's how I want it to look: box-shadow: 0 0 5px #5cd05 ...

Utilizing NextJS to retrieve cookie data within React components

Currently, I am working with a Next.js frontend and an Express backend. For authentication, I am utilizing cookies and have set up protected routes using Next.js middleware. The next step in my project involves accessing the cookie response within React ...

What could be causing the redirection to my php file in this particular contact form?

I have a contact form on my website that uses AJAX for submission. Everything seems to be working fine, but when the user clicks on the Submit button, they are redirected to the PHP file instead of staying on the page to see success or error messages. I wa ...

Express server failing to deliver static assets

I am currently developing an app using Express and socket.io, but I am facing an issue where my server is unable to locate the static files. Despite searching for solutions online and trying various methods such as referencing the public folder with expres ...

Execute JavaScript code a specified number of repetitions, incrementing the value of each number in the array by 1

This is the HTML structure that cannot be directly changed in the DOM, but can be modified with JavaScript by altering attributes and classes: <div class="parent"> <label class="child" for="label_1"> &l ...

Adding objects from an existing JSON file to an empty object in Node.js is a straightforward process

Looking to extract JSON data from a separate file and transfer it into a new object using Node JS. Despite trying various methods without success, I still can't figure out how to achieve this. Can anyone provide guidance or suggestions? Add new eleme ...

challenges encountered with the clearTimeout() method in vue.js

I am currently working on implementing a shopping cart using Vue, but I am encountering some challenges. As I am new to using this library, it is possible that I am making some basic mistakes. Here is the issue I am facing: When I add an item to the cart, ...

Generating webpack bundle from files located in a specific directory

I am encountering issues while attempting to compile and run a react application using the file public/src/index.js. My goal is to generate a distinct build from JavaScript files located within the directory public/design/albert/js. However, I am facing pa ...

Incorporate image into Vue.js form along with other information

I have been successfully sending the content of multiple fields in a form to the Database. Now I am looking to add an additional field for uploading images/files and including it with the other form fields, but I am unsure about how to accomplish this task ...

The error message "Access-Control-Allow-Origin" header is not present when making an Ajax call to ReactJS localhost

While following the ReactJS tutorial, I set up a local server using the following commands: >npm install -g http-server >http-server -c-1 After successfully starting the local server at http://localhost:8080, I encountered an issue when trying to ...

What is the process for generating a variable script within an HTML tag using document.write?

Here is the code snippet: <script>var posterimage=/images/videos/intro/iamge01.png;</script> <script>document.write('<video controls="controls" height="300" id="video-playlist" poster="VARIABLE" preload="none" src="video.mp4" wid ...

Utilize jQuery AJAX to showcase JSON data by handling the response of a POST request sent to a JSP

Displaying JSON Data Using JavaScript Code $(document).ready(function(){ $("button").click(function(){ $.ajax({ url:"jsonCreation.jsp", type:'post', dataType: 'json', ...

Stop Bootstrap IE menu from closing when scrollbar is clicked

When using IE, the dropdown menu closes when clicking on the scrollbar. However, it functions properly when scrolling with the mouse wheel. To see the issue in action and potentially offer a solution, you can visit this Codeply link: I'm seeking sug ...

Adding information to a MySQL database using a variable - What's the best way?

When I attempt to insert values defined in JavaScript at the beginning of the program, it seems to have an issue with me trying to input variables. Instead, it requires me to enter the raw name. The error message displayed is as follows: Error: ER_BAD_FI ...

What is the best way to input information into an object?

I am having an issue where I am trying to add data into an object, but I keep getting the error "push is not a function". Here is the object in question: var item = { "_id": { "$oid": "asdf976" }, "Categories": [{ "mainmodels": [{ "su ...

with every instance of an ajax request sent to a separate file

Currently, I have a forEach function that is printing the "local" column from a specific database: View image here Everything is working well up to this point, and this is the output I am getting: See result here Now, my goal is to send variables via P ...

Enlarge image when clicked

I need help creating a gallery page where users can click on an image to enlarge it, then navigate through the images using arrows on either side. I am not familiar with JavaScript, so could someone guide me on how to achieve this? Also, I would apprecia ...

Tips for resolving the ECONNRESET error during the installation of Electron?

I am encountering a challenge while attempting to install electron as I keep receiving an ECONNRESET error, despite trying various solutions: Attempted to install globally Tried removing the proxy. Tested a mirror address but uncertain if the address was ...