0

I have clickable div, made by addEventListener on element:

function expandTask() {
    const allTasks = document.querySelectorAll('.task-item');

    allTasks.forEach((task) => {
        task.addEventListener("click", () => {
                if(!task.classList.contains('active')){
                    task.classList.add('active');
                } else {
                    task.classList.remove('active')
                }
            })
    })
}

and I would like to put some buttons inside this clickable div, how can i make this work?

When i click on button, it still consider this as click on parent div.

3
  • Event bubbles by default. So if you include a button inside a div, it bubbles to the parent div and triggers the handler. So no need to do any extra thing, just make a button inside the div. But I don't know why you would want a clickable div, and a button inside it. Commented Jan 28, 2021 at 19:35
  • Do you want the button click to do something different than the div click? Commented Jan 28, 2021 at 19:41
  • @DipeshTimilsina While creating todo app, i have tasks lists and clicking on task expand more details, and on this task i want buttons like checkbox that make task complete, edit button or delete task. Commented Jan 28, 2021 at 19:46

1 Answer 1

1

You can create elements dynamically using document.createElement(tagName) and then use element.appendChild(element) to insert them in the document.

Bonus: you can use classList.toggle(className) if that suits your needs.

function expandTask() {
    const allTasks = document.querySelectorAll('.task-item');

    allTasks.forEach((task) => {
        task.addEventListener("click", () => {
            task.classList.toggle('active');

            let newDiv = document.createElement("DIV");
            newDiv.innerHTML = "Some text you want to add";
            task.appendChild(newDiv);
        });
    })
}

Edit: as said in the comments, the event bubbles up by default, you can understand more about it here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.