TJ Weems
TJ Weems

Reputation: 1114

How To Edit rowIndex Of Table Row Using Javascript

This might be unconventional but I was wondering how can I edit the index of a table row?

So I can grab the current rowIndex of a table row like so

var rowIndex = document.getElementsByClassName('edit-engagement-row')[0].rowIndex

But if I want to then change the rowIndex like so

var rowIndex = document.getElementsByClassName('edit-engagement-row')[0].rowIndex
rowIndex = index

I get the following alarm

Uncaught TypeError: Cannot assign to read only property 'rowIndex' of object '#<HTMLTableRowElement>'

Upvotes: 0

Views: 1237

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48693

You can detach the child and

function detach(element) {
  return element.parentElement.removeChild(element);
}

function move(src, dest, isBefore) {
  dest.insertAdjacentElement(isBefore ? 'beforebegin' : 'afterend', detach(src));
}

function children(element, selector) {
  return element.querySelectorAll(selector);
}

function child(element, selector, index) {
  return children(element, selector)[index];
}

function row(table, index) {
  // Generic Version: return child(table.querySelector('tbody'), 'tr', index);
  return table.querySelector('tbody').querySelector(`tr:nth-child(${index + 1})`);
}

function moveRow(table, fromIndex, toIndex, isBefore) {
  move(row(table, fromIndex), row(table, toIndex), isBefore);
}

// Move "Eve" (index = 2) to be before "Jack" (index = 0)
moveRow(document.querySelector('table'), 2, 0, true);
table {
  border-collapse: collapse;
  width: 50vw;
  margin: 0 auto;
}

table, th, td {
  border: thin solid grey;
}

th, td {
  text-align: center;
}
<table>
  <thead>
    <tr><th>Firstname</th><th>Lastname</th><th>Age</th></tr>
  </thead>
  <tbody>
    <tr><td>Jack</td><td>Brown</td><td>42</td></tr>
    <tr><td>Jill</td><td>Smith</td><td>50</td></tr>
    <tr><td>Eve</td><td>Jackson</td><td>94</td></tr>
  </tbody>
</table>

Upvotes: 2

Related Questions