简体   繁体   中英

How to dynamically change ID attribute using Vanilla JavaScript

I am currently building a to-do list app.

I am using the insertAdjacentHTML method to add new items to the list and that works just fine. My problem remains on how to dynamically change the id attribute that it begins to increase by 1 as I add a new item to the list.

How can I solve that?

Here is the code:

function addTaskFunc() {

    const aTask = `
    <div class="task" id="task-0">
    <button class="done__btn">
        <i class="far fa-check-square"></i>
    </button>
    <p>${box.value}</p>
    <button class="priority">Make priority</button>
    <button class="cancel__btn">
        <i class="far fa-times-circle"></i>
    </button>

    </div>
`;
    const x = box.value;
    taskList.insertAdjacentHTML('afterbegin', aTask);
    box.value = '';
}

newTask.addEventListener('click', addTaskFunc); 

Add a counter ( idCounter ) and use it in the template literal, and increment it whenever you use it:

let idCounter = 0;

function addTaskFunc() {
  const aTask = `
    <div class="task" id="task-${idCounter++}">
    <button class="done__btn">
        <i class="far fa-check-square"></i>
    </button>
    <p>${box.value}</p>
    <button class="priority">Make priority</button>
    <button class="cancel__btn">
        <i class="far fa-times-circle"></i>
    </button>

    </div>
`;
  const x = box.value;
  taskList.insertAdjacentHTML('afterbegin', aTask);
  box.value = '';
}

You can use a variable that increments every time a new task is added.

This approach is slightly different because it provides a TaskBuilder constructor, this is only to avoid global variables and potential clashes with other scripts.

function TaskBuilder() {
  if (!new.target) {
     throw new Error("Illegal argument error, you should call this function as a constructor.");
  }
  this.currentId = 0;
}

TaskBuilder.prototype.addTask = function() {
  const aTask = `
    <div class="task" id="task-${this.currentId}">
    <button class="done__btn">
        <i class="far fa-check-square"></i>
    </button>
    <p>${box.value}</p>
    <button class="priority">Make priority</button>
    <button class="cancel__btn">
        <i class="far fa-times-circle"></i>
    </button>

    </div>
`;
  const x = box.value;
  taskList.insertAdjacentHTML('afterbegin', aTask);
  box.value = '';

  this.currentId++;
};

const taskBuilder = new TaskBuilder();
newTask.addEventListener('click', function() {
  taskBuilder.addTask();
});

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