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

What is preventing Google Chrome from locating my app.js file?

Just embarking on my journey to learn Nodejs through a basic app. Strangely, Google Chrome is unable to locate my app.js file in the /assets/js.app directory. Reviewing the paths I've configured, it seems everything is set up correctly. Instead of d ...

Is it possible to transmit identical data from a form to two distinct actions in Symfony5?

UNIQUE LOGIN TEMPLATE {% extends 'base.html.twig' %} {% block title %}Welcome to the Login Page!{% endblock %} {% block body %} {% if error %} <div>{{ error.messageKey|trans(error.messageData, 'security') }}</div& ...

Creating a Form Layout with Bootstrap - Organizing Text Boxes and Text Areas

https://i.sstatic.net/oqRwR.jpg In the image above, I need to adjust the position of the textbox to align it with the TextArea. Is there a Bootstrap class that can help me achieve this? My current version of Bootstrap is 3.3.6. HTML &l ...

Deactivate the form element when a user selects another button

I am facing an issue with two buttons that are linked to the same modal form. Here is the code snippet for the form: <form name="addUser" ng-submit="(addUser.$valid) ? add() : '';"> <div class="form-group has-feedback" ng-class="ad ...

Is there a convenient method to combine arrays of objects in JavaScript using ellipses or an equivalent approach?

let array = [ {id: 1, data: {foo: "bar 1"}}, {id: 2, data: {foo: "bar 2"}} ]; //If ID doesn't exist, add new element to the array array = [...array, {id: 3, data: {foo: "bar 3"}}] console.log(array); //If ID exists, replace data object with new ...

Leveraging Material-UI in Electron Environment

I'm currently working on an electron app using React and incorporating Material-UI for the user interface. I've added a datepicker and timepicker to a component, but when clicking on the input in the electron app, nothing happens. I'm unsure ...

Why is the autocomplete minlength and maxheight not functioning properly in MVC?

After entering a value in the text field, data from the database appears but adjusting the height and width of the list box seems to be a challenge. I have set the parameters like minLength: 0, maxItem: 5, but it doesn't seem to make a difference. ...

"Encountering a restricted URI error when attempting to load a text file using AJAX

After reviewing the recommended link, I found myself struggling to grasp the suggestion to "Use Greasemonkey to modify Pages and start writing some javascript to modify a web page." Currently, I am encountering an error when loading a text file using $.aj ...

Modifying the HTML file won't be immediately visible in browsers

I encountered a frustrating issue while working on my website. Despite making changes to the code, the browsers are not reflecting the updates. This problem is occurring in Internet Explorer, Google Chrome, and Firefox. Initially, I had a div with a link ...

What are the best situations to utilize bootstrap and when should you avoid it?

When it comes to web development, there is often a debate on whether to use Bootstrap or custom CSS for designing a website. For my school project, I am tasked with creating a homepage and contact page using Bootstrap primarily. However, we are also requir ...

Ensure that the user's browser cache is cleared after deploying a new version on Firebase hosting

Utilizing create-react-app for my front end scripts and firebase hosting for deployment has been smooth overall. However, I've encountered an issue where updates to CSS and HTML files don't always reflect on the domain until I manually clear the ...

Creating a gap between two rows within a Bootstrap table

Is there a way to create space between two bootstrap table rows? I am looking for something like this: --------- | A B | --------- --------- | C D | --------- --------- | E F | --------- Here is the code snippet: <script src="https://cdnjs.c ...

The Jquery watermark extension in IE9 is capable of transmitting the watermark as the primary value of the form

I have integrated a plugin into my project. The plugin can be downloaded from this link. However, I am facing an issue where the watermark value is being submitted as the textbox's value in Internet Explorer 9. How can I resolve this problem? Intere ...

The Element should take up the entire page with the exception of a 20px margin

I am struggling to create an element that covers the entire page except for a 20px margin on all sides. I have tried implementing a solution using this code, which works in webkit browsers and Firefox but seems to have issues with Internet Explorer (10) an ...

Start progress bars on several divs that share a common class

I'm attempting to utilize the ProgressBar.js Plugin on multiple div elements that share the same class form-progress This is my HTML code: <div class="form-progress"></div> And here is the corresponding JavaScript code: var form_pr ...

centering headers using tailwind styles

I am facing a challenge with positioning my main title, logo, and subtitle. I want the subtitle to be centered regardless of the logo's width. Currently, the position of the sub title changes based on the logo's width, resulting in it not aligni ...

tips for repurposing a jquery function

Similar Question: JQuery: Issue with $(window).resize() not triggering on page load In my jQuery code snippet below, I am trying to make a function work both on window resize and page load without duplicating the code. The current implementation works ...

What is the correct way to format a URL in an AJAX request using CodeIgniter in PHP?

I'm just starting out with CodeIgniter and I'm having trouble retrieving data from the controller using an AJAX request. I think I may have made a mistake in writing the URL for the controller function in the AJAX call. Below is the code for my ...

Is there a method to prompt the browser to retain form data when using the back button?

Having a puzzling problem. I've developed a sophisticated quote form for our company that utilizes ajax to display prices for products based on user input. There are 6 hidden fields set up as follows: productname1 productname2 productname3 and the ...

Making AngularJS 'PUT' requests: The process of submitting only the data in a form

I am facing an issue while updating user data in Angular. When I send a 'PUT' request, the entire user $scope is being sent instead of only the fields visible on the form. To retrieve and update the data, I am using a Factory. Below is my edit f ...