Looking to access all parent elements of the <li> tag when it is clicked?

Currently, I am working on designing dynatree and the nodes are structured within ul and li tags. However, I am encountering an issue where I am unable to retrieve the parents of the clicked li element.

Below is a snippet of my HTML code:

<ul class="bulk">
    <li>gp1
        <ul>
            <li>gp2
                <ul>
                    <li>gp3
                        <ul>
                            <li>c1
                            <li>c2
                            <li>c3
                        </ul>
                    <li>gp4
                </ul>
            </li>gp5
                <ul>
                    <li>gp6
                        <ul>
                            <li>gp7
                                <ul>
                                    <li>c4
                                        <ul>
                                            <li>c5
                                            <li>c6
                                        </ul>
                                </ul>
                            </li>gp8
                            <li>gp9
                        </ul>
                    <li>gp10
                </ul>
        </ul>
</ul>

Here is a jQuery method I have implemented:

$('ul.bulk li').click(function(e) 
{ 
    alert(e.html());
});

You can view the implementation in action on this fiddle: http://jsfiddle.net/raghavendram040/ojnLrcjz/

The issue I am facing is that when I click on 'gp3', it alerts me 3 times instead of its parent elements like gp1 and gp2. All the li and ul elements are placed dynamically except for the tag. Any help or guidance on how to solve this problem would be greatly appreciated.

Answer №1

If you want to achieve something similar, consider the following code snippet:

$(function () {
    $('ul.bulk li').on('click', function (event) {
        if($(event.target).is(this)){
            $(this).parentsUntil('.bulk', 'li').each(function(){
                alert(this.firstChild.nodeValue)
            })
        }
    });
});

Check out the demonstration here: Fiddle

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

Activate datepicker upon choosing a symbol

If the symbol field is selected, the datepicker is enabled. If the symbol field is not selected, the datepicker remains disabled. <script src="{{asset('js/libs/jquery.js')}}" crossorigin="anonymous"></script> <link href="https:/ ...

Is it possible to modify the 3D object within WebGL using Three.js only in certain scenarios, such as adding textures or moving the mouse?

Utilizing a 3D object exported from Blender, specifically cylinder.obj, I have successfully implemented its rendering on the screen with the help of Three.js. The functionality to rotate the object using mouse input has also been integrated. This entire vi ...

Execute a PHP SQL query when a link is clicked

To trigger a SQL query when a link is clicked, I have implemented the following code: mainpage.php: function deleteImage1() { $.post("delete_image.php", { num:1, id:<?php echo $id; ?> }, function(data,status){ alert("Data: " + data + "\n ...

Issue with Jquery's Child Selector not functioning without any apparent cause

My goal is to display or hide the child class when the parent is hovered. I have multiple classes set up, similar to what is discussed in Jquery $(this) Child Selector. Unfortunately, for some mysterious reason, it is not working. This is what I currentl ...

"Utilizing Bootstrap's Table Features within the Moodle Platform

Hey there! I'm currently in the process of updating a client's Moodle website. Our goal is to create responsive tables on the homepage, but I've encountered some challenges. Due to conflicts with other Moodle libraries, I wasn't able to ...

Why does the UseEffect hook in next.js result in 2 fetch requests instead of the expected 1?

I am encountering an issue where my code is triggering two requests to my API using the GET endpoint. Unfortunately, my understanding of useEffect() is not deep enough to pinpoint where the problem lies. I want to avoid putting unnecessary strain on the ...

What is the process for invoking a method that accepts a List<string> type parameter through an ajax call

I have been trying to figure out how to make an AJAX call to a C# method from jQuery, but it seems that the code below is unable to send the value to the "SessionTemplate(List list)" method. How can I successfully pass a value of type List? [HttpPost] pub ...

Fundamentals of object property in jQuery and Javascript

Currently working on creating a new property named startPosition and setting the top property to equal the button's current top value in CSS. Below is the jQuery code snippet: var morphObject = { button: $('button.morphButton'), c ...

The flow of data from the SQL database to the Flask/Jinja template seems to be blocked

My HTML page is rendering fine, but I'm having trouble displaying the database. The database is already set up, and I want to loop through it in the template, but nothing shows up. main.py: from flask import Flask, request, redirect, render_template ...

Using node appendChild() in HTML for animating elements

As someone who is brand new to the world of web development, I am trying my hand at creating a webpage that expands as a button is clicked. Recently, I stumbled upon this helpful link which includes some code: The HTML code snippet is: <ul id="myList" ...

Swap out the text of one element with a different text content found within the DOM

I have a web app that features a template for displaying a list of books retrieved from the server using Python (Flask). The information about the books, including titles, IDs, and authors' names, is stored in the variable "books" which I then loop ov ...

Ensure that both the div element and its contents are restricted to a maximum width of

I'm having trouble arranging the display of information next to a plant image. I want to ensure that the information stays on the right side of the image when the screen reaches a specific minimum width. The issue arises when the information includes ...

javascriptretrieve the second class from the element

HTML Code : <span class="button" onclick="javascript:buttonClicked();">Log In</span> <div class="modal-bg" style="display: none;"> <div class="modal"> <span>Log In<a href="#close" class="close">&# ...

Is there a formatting error when pulling data from an API using Angular?

The data retrieved from the API follows this format: { “array1”:[ {"id”:1, ”someProperty”:”A"}, {"id":2, "someProperty”:”B”} ], “array2”:[ {"id”:1, ”anotherProperty”:”foo”, ”lastProperty”:”foo2”}, ...

JQuery trick: How to create a looping animation

I am trying to figure out how to create a looping animation with jQuery, specifically one horizontally moving rectangle. I would also like the animation to start automatically once the page has fully loaded, rather than needing to be triggered by clicking ...

Ways to automatically preload all tabs using jQuery

Is there a way to pre-load both ajax tabs when I have 4 tabs, with the first 2 being loaded with ajax and the last 2 static? Currently, only the first tab is automatically loaded, while the second one loads upon clicking. I want both to be loaded so that ...

CSS tip: Create a trendy design by adding a slanted border to the last

I need help creating a unique menu list with a white border design. The borders should all be straight by default, except for the last border which must be slanted. ul { background-color: #183650; } li { list-style: none; display: inline-block; b ...

Challenges regarding placement and z-index are causing issues

Currently, I am attempting to make the menu overlap the content on my webpage. However, I am facing an issue where it moves the content box instead of overlapping it. I have already experimented with the position: relative concept, but unfortunately, the ...

Creating a customized function in javascript/jquery with the ability to override it

Currently, I am utilizing Visual Studio for writing JavaScript/jQuery. For instance, when I input: $('#selector').text('foo') and then highlight text and hit F12, Visual Studio directs me to the file jquery-2.2.3.intellisense.js, auto ...

Sending a Json object back to an Ajax request made to a webMethod

I have been working on implementing an Ajax call method and an ASP.NET web method. The ASP.NET function I created is returning some values that I need to handle in the Ajax call. Despite trying various approaches, I have not yet succeeded in achieving th ...