JSFiddle - React, Tailwind, and code Playground
by ronilan
HTML
Answer to: <a href="https://www.reddit.com/r/javascript/comments/5aw6uq/swapping_html_table_elements_the_complete_object/">Reddit Question</a>
<hr>
<div class="queueSong">
<table class="qTable" id="qTable">
<tr>
<th>Song Info</th>
<tr>
<td>
<div>Horchata</div>
<button class="removeButton">X</button>
<button class="upButton">up</button>
<button class="downButton">do</button>
</td>
</tr>
<tr>
<td>
<div>White Sky</div>
<button class="removeButton">X</button>
<button class="upButton">up</button>
<button class="downButton">do</button>
</td>
</tr>
<tr>
<td>
<div>Holiday</div>
<button class="removeButton">X</button>
<button class="upButton">up</button>
<button class="downButton">do</button>
</td>
</tr>
<tr>
<td>
<div>Call Me Maybe</div>
<button class="removeButton">X</button>
<button class="upButton">up</button>
<button class="downButton">do</button>
</td>
</tr>
<tr>
<td>
<div>Never Gonna Give You Up</div>
<button class="removeButton">X</button>
<button class="upButton">up</button>
<button class="downButton">do</button>
</td>
</tr>
<tr>
<td>
<div>Can I get a Witness</div>
<button class="removeButton">X</button>
<button class="upButton">up</button>
<button class="downButton">do</button>
</td>
</tr>
</table>
</div>
JavaScript
function removeTableRow(removeMe) {
var userInput = confirm("Are you like totally sure?");
if (userInput) {
removeMe.parentNode.removeChild(removeMe);
}
}
function moveTableRow(moveMe, direction) {
var els = document.getElementById('qTable').getElementsByTagName('TR');
var max = els.length;
var i = 1; // ignore the header row
// go over the nodes
while (i < max) {
// match
if (els[i] === moveMe) {
// up or down
if (direction > 0) {
// ignore the header row
if (i > 1) {
els[i].parentNode.insertBefore(els[i], els[i - 1]);
}
} else {
els[i].parentNode.insertBefore(els[i], els[i + 2]);
}
break;
}
i++;
}
}
// find the parent TR of a child
function parentRow(el) {
while (typeof el.tagName !== 'undefined') {
if (el.tagName === 'TR') {
break;
}
el = el.parentNode;
}
return el;
}
// listen to clicks in the table
// ignore anything not on button
document.getElementById('qTable').addEventListener('click', function(e) {
if (e.srcElement.classList.contains('downButton')) {
moveTableRow(parentRow(e.srcElement), -1);
}
if (e.srcElement.classList.contains('upButton')) {
moveTableRow(parentRow(e.srcElement), 1);
}
if (e.srcElement.classList.contains('removeButton')) {
removeTableRow(parentRow(e.srcElement));
}
})