Tips for using jQuery to add or append a class to the final li element

I am currently struggling to understand why the last child of the li element is not being inserted into the last li. This module functions as a treeview, and my main objective is to add a class to the last li.

Let me demonstrate with some sample code and illustrations below:

As you can see, the added class is on a different li element when it should be on the check mark.

Problem: The added class ('last') is not appearing on the correct last li.

I have two HTML pages:

  1. posting.blade.php
  2. manage_child.blade.php

https://i.sstatic.net/mZLsf.png

posting.blade.php:

<ul id="tree1">
    @foreach($categories as $category)
        <li>
            {{ $category->title }}
            @if(count($category->childs))
                @include('/SuperAdmin/manage_child',['childs' => $category->childs])
            @endif
        </li>
    @endforeach
</ul>

manage_child.blade.php:

<ul>
@foreach($childs as $child)
    <li>
        {{ $child->title }}
    @if(count($child->childs))
        @include('/SuperAdmin/manage_child',['childs' => $child->childs])
    @endif
    </li>
@endforeach
</ul>

Treeview Js:

$.fn.extend({
    treed: function (o) {

        var openedClass = 'far fa-minus-square';
        var closedClass = 'far fa-plus-square';

        if (typeof o != 'undefined'){
            if (typeof o.openedClass != 'undefined'){
            openedClass = o.openedClass;
            }
            if (typeof o.closedClass != 'undefined'){
            closedClass = o.closedClass;
            }
        };

        // Rest of the JS code...

    }
});

// Initialization of treeviews

$('#tree1').treed();

CSS:

#tree1, #tree1 ul {
    margin:0;
    padding:0;
    list-style:none
}

// Rest of the CSS code...

Additionally, I want to remove the yellow background of the children with the .branch class.

https://i.sstatic.net/DAPas.png

Answer №1

To properly navigate through the tree structure, it is essential to descend downwards and select the final item. This action involves gathering all instances of li, singling out the last one, and assigning a specific class to it. Instead of employing the .is statement, implement the following code snippet:

branch.find('li').last().addClass('last');

If you specifically require this functionality based on the element that has been currently clicked, utilize the alternative method as shown below:

$(this).find('li').last().addClass('last');

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's the best way to resolve the JavaScript conflict arising from Prototype and jQuery?

Similar Issue: jQuery & Prototype Conflict It seems that I am encountering a compatibility issue between jQuery and prototype, specifically when using Internet Explorer 8. You can view the problem here: In IE8, the FAQ questions are not expandin ...

Create a sleek Bootstrap 4 webpage featuring a fixed footer and navigation bar. However, the challenge lies in ensuring that the content fills the

Currently, I am in the process of creating a template page that includes a navbar and a footer with the intention of adding additional columns within the main div (container-fluid) at a later stage. However, I have encountered two issues that I cannot seem ...

Extract words with specified tags from HTML using Python and return them as a list

Is there a simple way to parse HTML, extract the text, and generate a list of tags associated with each word or snippet of text? For instance, in the given HTML code: <em>Blah blah blah</em> blah again <i>and then again</i> The de ...

Mismatch between the format and extension of an HTML table when exporting to Excel

I've been working on a function that converts an HTML table into an Excel document. Unfortunately, when I try to open the file in Excel, I receive an error message that says: The file format and extension of 'something.xls' don't mat ...

Tips for successfully transferring a JSON object from jQuery to a JavaScript function

Can you help me with accessing data in a JavaScript function after populating it dynamically on an HTML page through an Ajax call? Issue: I am trying to invoke a JavaScript function when clicking on a button after populating the data. However, I am facing ...

Populating a span tag with data retrieved through Ajax

I encountered an issue with updating the totalDraftSalePrice HTML tag after a successful AJAX call. The data returned includes a field called SubtotalBasePrice, which I can visualize in JSON format, but for some reason, I am unable to update the HTML tag w ...

Using HTML5 datetime-local to only accept dates in the format Y-m-d

I am currently working on a form that includes a datetime-local input field. <input type="datetime-local" id="datetime" /> After clicking on the today button, the date is automatically set to today's date like this: 2018-11-05 --:-- However ...

Stop the content inside a div box from wrapping around the edges when using Bootstrap

Utilizing bootstrap to structure a webpage, I have organized three divs next to each other within a row. The widths of the divs are set as follows: 2 columns, 6 columns, and 4 columns in a 12 column layout. The middle div has a minimum width defined. As a ...

Ways to differentiate between a single date and multiple dates using PHP

Is there a way to compare two dates in PHP? I have two different dates: one is from the database and the other is selected from a Datepicker. $dbdate = 01-06-201402-06-201403-04-201405-06-2014 //DB date $datepickerDate = 06-06-2014 //Datepicker date. ...

Select and activate a single input from multiple options in Angular

I have multiple input fields with corresponding buttons that enable the input when clicked. I would like the behavior of the buttons to work in such a way that when one button is clicked, only that specific input field is enabled while the others are disab ...

Linking the User Interface to the Controller and Database

My UI requires a text field where users can input the streamId (e.g. 1, 2, 3) and then click 'ok' to display a table on the screen from the database based on the streamId value. ...

Ensuring IconButton is perfectly aligned with Text in one straight line

I want to display IconButtons alongside plain text in a single block of text, but the result didn't turn out as I had hoped. Here is what I attempted: JS(ReactJS): <div> <span> <h3>Title</h3> <IconButton className ...

Tips for ensuring that flex-box children can scroll properly

I'm having trouble getting the content to scroll correctly while dealing with nested flex-box structures. Below is my CSS code: html,body,#root{ width:100%; height:100%; padding:0; margin:0; } .flex-fill{ height:100%; width:100%; ...

What is the best way to exchange the chosen selection within 2 select elements?

I have been trying to swap the cities in my select fields using two select elements, but for some reason, it is not working when the button is clicked: <div class="select-wrapper"> <select class="airport-select__departure"> <o ...

Exploring the Power of Websharper with Sitelets and Forms

I have been working on developing a form using Websharper to gather user input. Currently, I have identified three actions for my website: type MyAction = | [<CompiledName "">] Index | [<Method "POST">] GetUser of username : string ...

Google Sheets displaying blank values after submission via an AJAX call

I have been working on transferring data from my web app to a Google spreadsheet and I am encountering some issues. I followed the script provided by Martin Hawksey, which can be found here: https://gist.github.com/mhawksey/1276293 Despite setting everyth ...

The margin-left and margin-right in HTML CSS are not cooperating to center a div

I'm currently diving into the world of CSS and HTML, but I've hit a roadblock. The margin-left and margin-right in the ".logo" div class are refusing to center the div as expected. Despite conducting research and meticulously checking over the co ...

Is there a way to display a message in a div container instead of using the alert box when there is a successful ajax response?

Hey there, I'm currently working on implementing error validation handling for a custom form that I've created. I'm looking to display the error messages in a designated div rather than using the standard browser alert box. Since I'm fa ...

Creating a dynamic full-width background image that adjusts its height according to the content: a step-by-step guide

Currently, I'm attempting to apply a background image to a webpage that spans 100% width in order to adjust to the viewport size. The method I am using involves placing an image directly after the body tag with the subsequent styling: img#background ...

Inverted CSS Shadow Box

I thought I had a good grasp on how CSS shadow-box works, but it seems I was mistaken. Could someone provide me with a visual explanation of why the <hr/> looks the way it does here? Take a look at style 13: https://codepen.io/ibrahimjabbari/pen/ozi ...