javascript - 在已知 ID 的表行之前或之后添加表行

标签 javascript html html-table

在这样的表中:

<table>
<!-- Insert Row of bun here -->
  <tr id="meat">
   <td>Hamburger</td>
  </tr>
<!-- Insert Row of bun here -->
</table>

function AddBefore(rowId){}
function AddAfter(rowId){}

我需要在不使用 jQuery 的情况下创建方法。我熟悉 jQuery 中的 append after 和 append before ..但我坚持使用纯 js。

最佳答案

使用

function AddBefore(rowId){
    var target = document.getElementById(rowId);
    var newElement = document.createElement('tr');
    target.parentNode.insertBefore(newElement, target);
    return newElement;
}

function AddAfter(rowId){
    var target = document.getElementById(rowId);
    var newElement = document.createElement('tr');

    target.parentNode.insertBefore(newElement, target.nextSibling );
    return newElement;
}

关于javascript - 在已知 ID 的表行之前或之后添加表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4515237/

相关文章:

javascript - 使一个 CSS 对象在一个盒子中居中

javascript - 带有 subview 的 Backbone.Marionette View

javascript - 构建计算器对象

html - 滚动div中的绝对底部位置?

css - 需要 html 帮助在一个唯一的选定 ID 下显示多行

python - 漂亮的汤和 table

javascript - Nativescript,如何在Javascript中使用这个java eventListener?

javascript - 允许混合内容编码错误

html - 如何在 css 的帮助下在下一行显示不间断的字符串

javascript - 生成具有随机背景色的表格单元格,然后显示背景色的十六进制值