Search code examples
javascriptdomgetelementbyid

Grab id of div, which is set as a number through template literal


Having a slight issue, trying to document.getElementById(), of a div, where the ID is set as a number.

You can see below, I'm looping through an object in my database and displaying each element in the DOM. I'm then giving each div, an id, (which is a number lastTask.id):

  function displayLastTask(lastTask) {
    console.log(lastTask);
    individualTasks +=
      `<div class="todoStyle">
        <p>Date: ${lastTask.date}: Task: ${lastTask.todo}</p>
        <p><button class="deleteButton" id=${lastTask.id}>Delete</button>
      </div>`;
    tasksContainer.innerHTML = individualTasks;
    return tasksContainer;
  }

I'm doing this, because later, I want to grab my delete button by its ID/object array number. (And only delete an object in the database, if its ID matches).

Anyway, the question I have, is how can I do a document.getElementById(), if it is a number? toString didn't work. Not sure if this is possible at all, if the ID is a number...

Here's what I'm trying:

    for (var i = 0, len = res.length; i < len; i++) {
      lookup[res[i].id] = res[i];

      const id = toString(res[i].id);

      document.getElementById(id).addEventListener('click', function(event){
        event.preventDefault();
        console.log('clicked');
      });
    }

Which returns the following error:

Uncaught (in promise) TypeError: Cannot read property 'addEventListener' of null

Have tried a few variations with no luck.


Solution

  • You shouldn't add an event listener to every single item. You can do this with event bubbling.

    Just add an event listener to a parentNode of your element. E.g.

    document.querySelector('#parent').addEventListener('click', event => { 
        console.log(event.target.parentNode.id); 
    })
    

    If for some reason you have to select a parent over the direct parent of that element, because you are creating the parent of your item more than once, you just log the following: console.log(event.target.parentNode.parentNode.id);.

    If it's even higher up, you just keep adding parentNodes.

    Just play around with those settings until you find what you were looking for.

    Hopefully, my explanation was understandable.