How to append an element to a specific div - Vanilla JS?

42 Views Asked by At

I'm new here - and also in Javascript, and I'm creating this ToDo List - I've been trying to just use vanilla JS. The idea is that the user can create their own task categories, and these will be arranged as boxes on the screen - dynamically creating an element in the DOM with class of the same name. Also these categories appear in a Select menu next to Inputs. My difficulty is how to add these tasks within the specific boxes for each - e.g: 'Training Sesh' inside the 'Workout' box, targeting the correct classes.

            <div class="activities" id="boxCards">
                <div id="box" class="Workout">
                    <div class="catName">
                        <h3>Workout</h3>
                    </div>
                    <div class="taskAction">
                        <p class="taskDesc">Training sesh at 4pm - </p>
                        <img src="calendar_month_FILL0_wght400_GRAD0_opsz24.svg" alt="calendar">
                        <span class="taskDate">Today</span>
                        <div class="action-btn">
                            <img class="completed" src="done_FILL0_wght400_GRAD0_opsz24.svg" alt="done" title="Completed">
                            <img class="deleted" src="delete_FILL0_wght400_GRAD0_opsz24.svg" alt="delete" title="Delete">
                        </div>
                    </div>
                </div>
                <div id="box" class="Study">
                    <div class="catName">
                        <h3>Study</h3>
                    </div>
                </div>
            </div>

This is the JS Code so far:

let boxTask = document.querySelector('#box');
const taskLibrary = [];

function adiciona(){
    let newDiv = document.createElement('div');
    newDiv.classList.add('taskAction');

    let para = document.createElement('p');
    para.classList.add('taskDesc');

    let lastTask = taskLibrary[taskLibrary.length - 1];
    para.appendChild(document.createTextNode(Object.values(lastTask)[1]));

    newDiv.appendChild(para);
    boxTask.appendChild(newDiv);
}

Any help will be greatly appreciated... Thank you!!

enter image description here

1

There are 1 best solutions below

0
Paul Braganza On

You can invoke the function to add the new task in the category with a function parameter which later can use used to target the section where you would like to append the new task to.

example

   function AddTaskToSection(sectionIdentifier) {
   // create task 
   ...
   ...
   const targetSection = document.getElementById(sectionIdentifier);
   
   if (targetSection) {
    targetSection.appendChild(taskDiv);
   } else {
    console.error("Element with ID " + elementId + " not found.");
   }
 }