通过内部值检测 TD 元素并将其移动到最后

Detect TD element by inner value and move it to be last

尝试通过移动元素及其内容提高我的 ECMAScript 技能。关于我的场景,一旦 DOM 准备就绪,我想...

我的HTML 代码

<table id="myItems">
<tbody>
<tr>
  <td>...</td>
  <td>...</td>
  <td>...</td>
</tr>
<tr>
  <td>...</td>
  <td>...</td>
  <td>...</td>
</tr>
<tr>
  <td>...</td>
  <td>...</td>
  <td>...</td>
</tr>
<tr>
  <td><input id="item10"><label for="item10">House</label></td>
  <td><input id="item11"><label for="item11">None</label></td>
  <td><input id="item12"><label for="item12">Car</label></td>
</tr>
</table>

到目前为止我已经尝试过,但需要改进....

   //get table name
    const mtarget = 'myItems';

    //check if exists
    if (document.getElementById(mtarget)) {

        //make the swap
        function init() {      
            //if so, target the specific table
            const mtable = document.querySelector("#" + mtarget);
            const lastrow = mtable.querySelectorAll('tbody tr')[3];
            //within it, move the none <td> to the end of existing <tr>
            const tdorgNone = lastrow.querySelectorAll('td')[1];
            const tdcloneNone = tdorgNone.cloneNode(true);
            lastrow.appendChild(tdcloneNone);
            tdorgNone.remove();
        }

        init();

我觉得我很接近,但请注意我没有按标签值定位正确的 <td>。我需要通过了解内在价值来更深入地了解找到我想要的<td>。我如何在 2020 年通过 ECMAScript 改进此代码?

使用查询字符串,您可以非常简洁地 select 数组中您想要的 <tr> 的子项。然后,您可以 .find 带有标签的 <td> - 如果它存在,则只需在父级 <tr> 上调用 appendChild<td> 将被删除从它以前的位置放在底部。

const mtarget = 'myItems';
const tds = [...document.querySelectorAll(`#${mtarget} tr:nth-child(4) td`)];
const noneTd = tds.find(td => td.children[1].textContent === 'None');
if (noneTd) {
  noneTd.parentElement.appendChild(noneTd);
}
<table id="myItems">
  <tbody>
    <tr>
      <td>...</td>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <td>...</td>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <td>...</td>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <td><input id="item10"><label for="item10">House</label></td>
      <td><input id="item11"><label for="item11">None</label></td>
      <td><input id="item12"><label for="item12">Car</label></td>
    </tr>
</table>