Create dynamical classnames with index in Javascript

64 Views Asked by At

Can somebody tell me If I can create classnames with index in JS/JQuery(see example below)?

$(`<tr class='data${i}'><td id='value${i}'></td></tr>`).insertAfter('#tbl-geburtstage_row_title')

Here is the full code:

for (let i = 1; i <= Object.keys(birthdays).length; i++) {
            console.log(`query ${i}`)

            if ($(`tr.data${i}`).length & $(`#value${i}`).text() != "") {
                //$('td.data')[i].remove()
                //console.log('td.data' + [i] + ": successfuly added and filled")
            }
            else {
                if ($(`tr.data${i - 1}`.length)) {
                    $(`<tr class='data${i}'><td id='value${i}'></td></tr>`).insertAfter(`tr.data${i - 1}`)

                }
                else {
                    $(`<tr class='data${i}'><td id='value${i}'></td></tr>`).insertAfter('#tbl-geburtstage_row_title')


                }

            }
        }

Code Snippet:

if ($(`tr.data${i}`).length & $(`#value${i}`).text() != "") {
  //$('td.data')[i].remove()
  //console.log('td.data' + [i] + ": successfuly added and filled")
} else {
  if ($(`tr.data${i - 1}`).length) {
    $(`<tr class='data${i}'><td id='value${i}'>First Line</td></tr>`).insertAfter(`tr.data${i - 1}`)

  } else {
    $(`<tr class='data${i}'><td id='value${i}'>First Line</td></tr>`).insertAfter('#tbl-geburtstage_row_title')
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tbl-geburtstage">
  <tr id="tbl-geburtstage_row_title">
    <th class="tbl-geburtstage_th">Alles Gute zum Geburtstag wünschen wir...</th>
  </tr>
</table>
<table class="tbl-geburtstageWeekend">
  <tr id="tbl-geburtstageWeekend_row_title">
    <th class="tbl-geburtstage_th">Auch denen die letztes Wochenende Geburtstag hatten, alles Gute!</th>
  </tr>
</table>

1

There are 1 best solutions below

0
aleks8 On

To use variables in string, in that case using index from a for loop, use ``

So, To create a class with index this is the correct way:

$('<tr class=`banana${i}`></tr>').insertafter('#id')