Search code examples
javascripthtmlconditional-statementsconditional-rendering

How to add div with dynamic id with JavaScript


I am trying to create divs with Javascript:

var v = e[c].day;
        var m = g(new Date(t, n - 1, v))
          ? '<div id=`${v}/${v}/${y}` class="today" type="button" onclick="addRow()">'
          : '<div type="button" onclick="addRow()">';
        l.append(m + "" + '<span class="month">' + i[n-1]+ "</span>" + "" + v + "</div>");

So what I am trying to do is giving the id to the divs with the date and when I try to do like this id=${v}/${v}/${y} it is being written exactly like this: ${v}/${v}/${y} instead the date. So apparently, t is a year, n is a month and v is a day. So how can I give them an id like this ${v}/${v}/${y}?


Solution

  • Surround the whole string with backticks:

    `<div id="${v}/${v}/${y}" class="today" type="button" onclick="addRow()">`
    

    See What are valid values for the id attribute in HTML?.