Discover the seamless technique for adding and removing nodes within a list through the power of onclick JavaScript

Two images are needed for each folder. The first image will create a subfolder when clicked, while the second image will delete the folder along with all its subfolders.

I have written some code that can create subfolders but cannot delete them. As a beginner in Javascript, I would appreciate any help

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Javascript Directory code</title>

<style>
ul 
{
list-style-image:url('closed.gif');
}
</style>


</head>

<body>
<ul>
    <li onClick="myFunction.call(this, event)" id="root">Root</li>
</ul>


<script language="javascript" type="text/javascript">
function myFunction(e)
{
    e.stopPropagation();

    var id=prompt("Enter Folder id");
    if (id != '' && id != null)
    {
        var val=prompt("Enter Folder name");
    }
    if (id != '' && id != null && val !='' && val !=null) 
    {
        var ulnode=document.createElement("UL"); //new ul<br>
        var node=document.createElement("LI"); //new li<br>
        node.id = id;//set id of new li <br>
        node.onclick = myFunction;//set onclick event of new li<br> 

        var textnode=document.createTextNode(val);//li value<br>
        node.appendChild(textnode);// new li + li value<br>
        ulnode.appendChild(node);// ul + li value

        this.appendChild(ulnode);
    }
}
</script>

</body>
</html>

Answer №1

Here is a potential solution:


    function addFolder(e)
    {
        e.stopPropagation();

        var folderId = prompt("Enter Folder ID");
        if (folderId !== '' && folderId !== null)
        {
            var folderName = prompt("Enter Folder Name");
        }
        if (folderId !== '' && folderId !== null && folderName !== '' && folderName !== null) 
        {
            var newULNode = document.createElement("UL");
            var newNode = document.createElement("LI");
            newNode.id = folderId;
            newNode.onclick = addFolder;
            var newLink = document.createElement("A");
            newLink.innerHTML = "---";
            newLink.onclick = removeNode;
            newNode.appendChild(newLink);

            var textNode = document.createTextNode(folderName);
            newNode.appendChild(textNode);
            newULNode.appendChild(newNode);

            this.appendChild(newULNode);
        }
    }

    function removeNode(e){
        e.stopPropagation();
        var element = e.target || e.srcElement;
        var parentToRemove = element.parentNode.parentNode;
        parentToRemove.parentNode.removeChild(parentToRemove);
    }

Answer №2

Using jQuery, you have the option to remove a specific element from the DOM by calling $('#id-of-folder').remove(); inside a function.

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

Can anyone suggest a method for adding comments and improving the organization of a bower.json file?

Managing a large project with numerous bower dependencies can be challenging. It's often unclear whether these dependencies are still being used or if the specified versions are necessary for a reason. It would be ideal to have the ability to add comm ...

Exploring the various possibilities of establishing multiple types of many-to-many relationships between two tables using Sequelize technology

Working with Sequelize in Node, I am dealing with Users and items. A user can interact with an item in various ways, such as voting or commending, which are distinct actions in this scenario. Initially, I considered having two separate many-to-many relati ...

Loading a div class dynamically with JQuery

It's clear to me there is an issue with my code, and I'm reaching out for assistance. Here is the problematic snippet that needs fixing. Currently, I'm encountering this error message: Uncaught TypeError: Cannot read property 'find&apos ...

Django: Error - < found where unexpected

Using a combination of Django and jQuery, I have implemented a file upload feature with AJAX. Everything seems to be working correctly - the files are successfully uploaded, reflected in the database, and stored on the server. However, upon completion of t ...

Webpack and terser reveal the names of the source files in the compressed output

Is there a way to stop source filenames from appearing in webpack output even when using Terser for minification? Illustration After minifying my production React app build, the resulting .js output file still contains original source filenames rather th ...

The deprecation of the componentWillReceiveProps lifecycle method in React components is posing challenges for developers utilizing

I am faced with a dilemma involving 2 components: one is responsible for adding new posts to an array of existing posts, while the other component maps through this array to display them on the page. My goal is to add the new post to the beginning of the ...

Increment count using jQuery upon clicking

I've got an HTML snippet that looks like this: var useful, cool, funny; '<ul data-component-bound="true" class="voteset'+data[i]['review_id']+'">'+ '<li class="useful ufc-btn" id="1">'+ & ...

Discover the nearest class and smoothly expand it with the slideDown function in jQuery

Hey there, I'm working on implementing a "View More" button on my page. The button will reveal another unordered list that currently has the class of "hidden-list". When the user clicks on "View More", I want it to slideToggle the hidden-list element ...

There are errors occurring in the getter I created within the vuex store.js file

Currently utilizing vuejs, vuex, and vuetify. Within this project there are 3 files in play and I will share the key sections here. The main objective is to showcase data associated with the route parameter. Despite my attempts in Product.vue as shown bel ...

Display a complete calendar with the date picker on a webpage

Currently experimenting with React to build a straightforward application. Admiring the appearance of full calendars from these date pickers (once clicked): Material-UI React-Toolbox Wondering if it's feasible to present the full calendar directly ...

What strategies can be used to efficiently perform Asynchronous Operations on a high volume of rows in a particular database table?

I am looking to perform Asynchronous Operations on every row of a specific database table, which could potentially contain 500,000, 600,000, or even more rows. My initial approach was: router.get('/users', async (req, res) => { const users = ...

Transforming a multi-dimensional array into a single level using Javascript

I'm currently faced with the challenge of converting a complex object array document into a single-level array. Here's an example: const data = [ { "id": 1, "name": "Beauty", "childre ...

Validation of the email address continually fails

I tried using a validation method that I found in various StackOverflow answers, but for some reason, the email always comes up as invalid. Because of this, the second condition is never being executed. Can someone point out what I might be misunderstand ...

Error: The variable lecturerFac has not been declared

Upon loading the html page, my controller fetches data from an API endpoint related to a course. The page is then populated with the course data. However, I also want to display information about the lecturer of the course (such as their image, name, descr ...

What strategies can be used to stop elements from reverting to their original state?

Hey there, I'm currently experimenting with animation and trying to create a cool two-step effect: 1. elements falling down and 2. pulsating on click. However, I've run into an issue where after the clicking action, the elements return to their o ...

Executing a JavaScript function within a C# file

I am implementing a JavaScript function within a C# file using the Page Load method <script type="text/javascript"> function googleMaps(aLocations, aTitles, aSummary) { $(document).ready(function () { $('#test').Goo ...

What's the best way to display the spinner while making an axios request?

When I put the spinner on a component did mount method with a setTimeOut method inside, it shows. However, I want the spinner to display only when there is no content on the page. After the axios request finishes loading, the page content should be shown i ...

Wordpress website fails to initiate Automate on Scroll (aos) functionality

I seem to be having trouble tackling any task that requires even the smallest amount of brain power. My current struggle is trying to integrate the AOS library into my Wordpress site. In an attempt to make it work, I inserted the following code into my fu ...

Using axios to call a web API method from within a ReactJS web worker

Currently, I am utilizing Web Worker alongside ReactJS (Context API schema) and encountering a particular issue. The design of my Web API and Context is outlined below: WebWorker.js export default class WebWorker { constructor(worker) { let code = ...

Is it possible for me to identify the original state of a checkbox when the page first loaded, or the value it was reset to when `reset()` was

When a webpage is loaded, various input elements can be initialized as they are declared in the HTML. If the user modifies some of the input values and then resets the form using reset(), the form goes back to its initially loaded state. I'm curious, ...