Search code examples
javascripthtmljqueryclassconditional-operator

add class to html inside backtick base on condition


i want to add class with the name -selected using ternaryoperator to my div with classname poll__option if the variable selectd equal to item.labe

   for (const item of data) {
      const template = document.createElement("template");
      const fragment = template.content;
      template.innerHTML = `
        <div class="poll__option">
      <div class="poll__option-fill"></div>
      <div class="poll__option-info">
        <span class="poll__label">${item.label}</span>
        <span class="poll__percentage">${item.percentege}</span>
      </div>
    </div>
    `;
    }

I expect that if selected==item.label it will add class with name -selected to my div


Solution

  • Use a variable and replace it in the template

    for (const item of data) {
      const template = document.createElement("template");
      const fragment = template.content;
      const myClass = selected==item.label ? 'poll__option-selected' : 'poll__option';
      template.innerHTML = `
        <div class="${myClass}">
          <div class="poll__option-fill"></div>
          <div class="poll__option-info">
            <span class="poll__label">${item.label}</span>
            <span class="poll__percentage">${item.percentege}</span>
          </div>
        </div>
      `;
    }