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.
You can create elements dinamycally 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.