简体   繁体   中英

Grab itemName data attribute from html element

I was trying to test a few novice tricks from a project tutorial. Wanted to create a small scale task app and ran into a weird problem. The last document.addEventListener below should theoretically call the closest element with the class name of ".name" should be detected since its in the same parent div with the button. However it is returning NULL. Am I applying the.closest() method wrong?

The event listener detects the button after everytime a task is created. Not sure why it returns NULL when, after creating the task via addTaskButton, the task with the class name of ".name". I even tried to create a data attribute id based off of the taskName itself to see if it'll detect, but still NULL / erroring.

const list = []

const container = document.querySelector('.container');
const itemContainer = document.querySelector('.item');
const addTaskButton = document.querySelector('.add-task');
const taskInput = document.querySelector('#task-name');


function renderTasks(){
    itemContainer.innerHTML = ''
    list.forEach(task => {
        const itemElement = document.createElement('div')
     
        itemElement.innerHTML = `
            <div class="name">
                ${task.taskName}
            </div>
            <button class="retrieval">Retrieve ID</button>
        `
        itemElement.dataset.itemName = task.taskName
        itemContainer.appendChild(itemElement);
    })
}

addTaskButton.addEventListener('click', (e)=>{
    e.preventDefault();
    list.push({ taskName: taskInput.value})


    renderTasks()
})



document.addEventListener('click', (e)=>{
    if(e.target.matches('.retrieval')){
        const taskName = e.target.closest('.name');
        console.log(taskName)
    }
})

Ok, I double checked the mdn article it says:

closestElement is the Element which is the closest ancestor of the selected element. It may be null.

That means it only looks for parents and parents of parents and so on, not 'siblings'.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM