jQuery - Enlarge Tree View to the level of the selected node

I am struggling to figure out how to expand the tree view up to a selected node level. If anyone has any ideas on how to accomplish this, please let me know.

For instance, if we click on 'Parent d' in the 'Category list', I want to expand the 'Tree View List' up to the 'Parent d' level. For more details, you can check Here

HTML

<h3>
Category list
</h3>

When clicking on any list item, the tree list should expand up to the selected level

<ul id='category'>
  <li li-id='1' id='1'>Parent 1</li>
  <li li-id='2' id='2'>Parent 2</li>
  <li li-id='3' id='3'>Parent 3</li>
  <li li-id='4' id='4'>Parent 4</li>
  <li li-id='5' id='5'>Parent c</li>
  <li li-id='6' id='6'>Parent d</li>
  <li li-id='7' id='7'>Parent a</li>
  <li li-id='8' id='8'>Parent b</li>
  <li li-id='9' id='9'>Parent e</li>
<li parent-id='5' li-id='10'>Parent x</li>
</ul>

Tree View List

<h3>
Node View
</h3>
<div class='tree'>
<ul id='ulCollapse'>
  <li parent-id='0' li-id='1'>Parent 1</li>
  <li parent-id='1' li-id='2'>Parent 2</li>
  <li parent-id='1' li-id='3'>Parent 3</li>
  <li parent-id='1' li-id='4'>Parent 4</li>
  <li parent-id='3' li-id='5'>Parent c</li>
  <li parent-id='3' li-id='6'>Parent d</li>
  <li parent-id='2' li-id='7'>Parent a</li>
  <li parent-id='4' li-id='8'>Parent b</li>
  <li parent-id='4' li-id='9'>Parent e</li>
<li parent-id='5' li-id='10'>Parent x</li>
</ul>
</div>

jQuery

//$('#ulCollapse li').hide();

$('ul li').click(function(){
    var nodeId = $(this).attr('li-id');
    alert(nodeId);
})

var $ul = $('ul');

$ul.find('li[parent-id]').each(function() {
  $ul.find('li[parent-id=' + $(this).attr('li-id') + ']')
    .wrapAll('<ul />')
    .parent()
    .appendTo(this)
});

DEMO

Answer №1

Although I am not a expert in javascript, I took a shot at solving your issue. Please check out the functional demo

var $ul = $('ul');
$(document).ready(function() {
  $ul.find('li[parent-id]').each(function() {
    $ul.find('li[parent-id=' + $(this).attr('li-id') + ']').wrapAll('<ul />').parent().appendTo(this) 
// This part of the code remains unchanged, but I've placed it inside document ready function for first-time execution only
  });
});
$('ul#category li').click(function() {
  $("#ulCollapse1").html(''); // A new div section was created here
  $("ul").removeAttr('class'); // Remove active classes 
  var nodeId = $(this).attr('id');
  arrangeNodes(nodeId); 
  $("#ulCollapse1").html($(".active").parent().clone()); // Obtain the parent element of the marked elements (which is 'li')
  $("#ulCollapse").hide(); // Hide the main treeview
});

function arrangeNodes(item) {
  $ul.find('li[parent-id=' + item + ']').parent().closest("ul").addClass("active"); // Locate the item and mark the closest ul as active (selected)
}

I hope this solution proves helpful.

Answer №2

I'm having trouble grasping the goal you're aiming for.

Could it be that :lt() is the solution you seek?

HTML

<h3>
List of Categories
</h3>

<ul id='category'>
  <li li-id='1' id='1'>Parent 1</li>
  <li li-id='2' id='2'>Parent 2</li>
  <li li-id='3' id='3'>Parent 3</li>
  <li li-id='4' id='4'>Parent 4</li>
  <li li-id='5' id='5'>Parent c</li>
  <li li-id='6' id='6'>Parent d</li>
  <li li-id='7' id='7'>Parent a</li>
  <li li-id='8' id='8'>Parent b</li>
  <li li-id='9' id='9'>Parent e</li>
  <li li-id='10' id='10'>Parent x</li>
</ul>
<br>
<br>

<h3>
View of Nodes
</h3>
<div class='tree'>
  <ul id='ulCollapse'>
    <li parent-id='1'>
      <ul>
        <li>Parent 1</li>
      </ul>
    </li>
    <li parent-id='2'>
      <ul>
        <li>Parent 2</li>
        <li>Parent 3</li>
        <li>Parent 4</li>
      </ul>
    </li>
    <li parent-id='3'>
      <ul>
        <li>Parent c</li>
        <li>Parent d</li>
        <li>Parent a</li>
      </ul>
    </li>
    <li parent-id='4'>
      <ul>
        <li>Parent b</li>
        <li>Parent e</li>
      </ul>
    </li>
    <li parent-id='5'>
      <ul>
        <li>Parent x</li>
      </ul>
    </li>
  </ul>
</div>

JS

$cats = $("#category");
$tree = $("#ulCollapse");
$tree.children().hide();

$cats.on("click", "li", function() {
  var nodeId = $(this).attr('li-id');
  console.info("NODE ID: ", nodeId);
  $tree.children().hide();
  var maxEq = $tree.children("[parent-id='" + nodeId + "']").index();
  maxEq < 0 && (maxEq = 0);
  maxEq++; //LTE since :lte() doesn't exist
  console.info("MAX EQ: ", maxEq);
  $tree.children(":lt(" + maxEq + ")").show();
});

FIDDLE ==> https://jsfiddle.net/x45j4fx6/1/

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

How about a custom-designed talking JavaScript pop-up?

Looking to customize the appearance (CSS, buttons...) of a "confirm" JavaScript dialog box while ensuring it remains persistent. The dialog box appears after a countdown, so it is crucial that it maintains focus even if the user is on another browser tab o ...

Obtaining images from JSON data and displaying them in a modal using AngularJS

Utilizing AngularJS to retrieve a JSON file: { "albumId": 1, "id": 1, "title": "accusamus beatae ad facilis cum similique qui sunt", "url": "http://placehold.it/600/92c952", "thumbnailUrl": "http://placehold.it/150/92c952" }, and showcasing it with ...

What's the process for setting a value in selectize.js using Angular programmatically?

Currently, I am implementing the AngularJS directive to utilize selectize.js from this source: https://github.com/kbanman/selectize-ng In my scenario, I have two dropdowns and my goal is to dynamically populate one of them called selectizeVat based on the ...

What is the best way to trigger a jQuery function after adding a <div> element through Ajax loading?

When I use Ajax to append a <div>, the dynamic inclusion of jQuery functions and CSS for that particular <div> does not seem to work. The insertion is successful, but the associated jQuery functions and CSS do not load properly. How can this be ...

A guide on uploading a photo to an existing mySQL database using a form

I already have a mySQL database containing basic client profiles, but now I want to add a picture for each record. I've set up a form with inputs and textareas to create new records. However, the field for the photo is stored as a blob. How can I inc ...

Difficulty navigating through pages on an iPad due to slow scrolling with JavaScript

My operation is executed within a scroll function, like this: Query(window).scroll(function(){ jQuery('.ScrollToTop').show(); // my operation. }); While my web page responds quickly to the operation, it seems slo ...

Ways to implement a backup plan when making multiple requests using Axios?

Within my application, a comment has the ability to serve as a parent and have various child comments associated with it. When I initiate the deletion of a parent comment, I verify the existence of any child comments. If children are present, I proceed to ...

Include an Open OnClick event in the React/JSX script

We have a dynamic menu created using JavaScript (React/JSX) that opens on hover due to styling. My inquiries are: Instead of relying on CSS for the hover effect, where in the code can I implement an OnClick event to trigger the menu opening using Java ...

Access view name in controller using Ui-Router

Utilizing the ui-router in AngularJS allows for the implementation of multiple views within the same page/state. While each view consists of a template, controller, and more, there appears to be no straightforward method of assigning a "resolve" function ...

Strategies for Dealing with 'No Search Results' in Your Search Functionality

I am currently facing an issue with displaying "No Results Found" when a user utilizes my search feature. The current problem is that "No Results Found" appears immediately on the screen and then disappears while a search query is being processed, only to ...

The anchor tag dwarfs the element it contains

I'm experiencing an issue on my website where the clickable area of my two images/buttons, labeled Get Started and Learn More, is larger than the actual image itself. I've wrapped the images with anchor tags to link to separate pages, but for som ...

Load HTML 5 video on a webpage after all other elements have finished loading

Hello there! I'm trying to figure out a way to load an HTML 5 video after the page has already loaded. Currently, the video pauses all site interaction until it's fully loaded, but I'd prefer to have it display an image first and then autopl ...

Listening for an event or using a CSS pseudo-class to detect when the scrollbar becomes

Are there any JavaScript event listeners or CSS pseudo classes that can detect when a scrollbar appears and disappears? For example, on Mac OS and Windows Internet Explorer 10 or newer, the scrollbars are hidden by default but appear when scrolling begins. ...

Establishing a unique title and favicon for non-HTML files on a website

Is there a way to specify a title and favicon for non-HTML files on a website? For instance, what if I have a link like https://example.com/files/image-or-something.png. In Chrome, the default behavior is to display the URL of the file as the title, with ...

Is there a way to launch Visual Studio Code using a web browser?

Is there a way to launch "Visual Studio Code" automatically upon clicking a button on my website? ...

Modify the appearance of the element that is currently chosen

I have a navigation menu and I would like to change the style of the element that is selected from the list in the navigation menu. I am using React with the Grid element from material-ui. NavigationMenu.tsx: import React, { useState, useEffect } from "r ...

An operator in rxjs that transforms an Observable of lists containing type X into an Observable of type X

Currently, I am facing a challenge while dealing with an API that is not very user-friendly using Angular HTTP and rxjs. My goal is to retrieve an Observable<List<Object>> from my service. Here's a snippet of the JSON output obtained from ...

While attempting to troubleshoot a program with mocha using the --debug-brk flag, it turns out that the debugging process actually

After setting up an open source project, I found that the mocha tests are running successfully. However, I am facing a challenge when trying to debug the functions being called by these tests. Every time I attempt to debug using 'mocha --debug-brk&apo ...

I'm curious about the correct method for updating a parent component using a shared service within the ngOnInit function in Angular version 13

There have been instances where I encountered a scenario multiple times, where I utilize a shared service within the ngOnInit of a component to update a value in another component, specifically its parent. This often leads to the well-known Error: NG0100: ...

Attempting to retrieve and save data in a variable using React Native

click here for image referenceI am a beginner in react-native and I recently attempted to use fetch to access an API. While I successfully managed to print the result on the console, I encountered difficulty in displaying it on a mobile screen. Below is a ...