简体   繁体   English

使用 JQuery 删除空的 tbody

[英]Remove empty tbody using JQuery

I have a lot of <tr class="form-items"> items inside my HTML code and I want to remove those tr's where <tbody> tag is empty.我的 HTML 代码中有很多<tr class="form-items">项目,我想删除那些<tbody>标记为空的 tr。

I've tried $("tbody:empty").closest('.form-items').remove() but it is not the good solution.我试过$("tbody:empty").closest('.form-items').remove()但这不是好的解决方案。

<tr class="form-items">
    <td colspan="3" class="forms-group">
        <table class="from-item-category">
            <tbody>
            </tbody>
        </table>
    </td>
</tr>
<tr class="form-items">
    <td colspan="3" class="forms-group">
        <table class="from-item-category">
            <tbody>
                <tr class="form-item-row">
                    <td class="fill-form">
                        <a>test #1</a>
                    </td>
                </tr>
            </tbody>
        </table>
    </td>
</tr>

:empty : Select all elements that have no children (including text nodes). :empty : 选择所有没有子元素的元素(包括文本节点)。

In your case you have text nodes.在您的情况下,您有文本节点。 Hence your selector cannot work.因此您的选择器无法工作。

Use this other approach (a tbody with no rows):使用另一种方法(没有行的 tbody):

$("tbody:not(:has(tr))")

The snippet:片段:

 $("tbody:not(:has(tr))").closest('.form-items').remove(); console.log($('table')[0].outerHTML)
 .as-console { height: 100%; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr class="form-items"> <td colspan="3" class="forms-group"> <table class="from-item-category"> <tbody> </tbody> </table> </td> </tr> <tr class="form-items"> <td colspan="3" class="forms-group"> <table class="from-item-category"> <tbody> <tr class="form-item-row"> <td class="fill-form"> <a>test #1</a> </td> </tr> </tbody> </table> </td> </tr> </table>

Search for first element in DOM, if exists and child contents of搜索 DOM 中的第一个元素(如果存在)及其子内容are empty then remove it, if not exit the loop.是空的然后删除它,如果不是退出循环。

console.log('Before deletion', document.body.innerHTML)
while (true) {
  var elem = document.getElementsByTagName('tbody')[0];
  if (elem && !elem.innerHTML.trim()) {
    elem.parentNode.removeChild(elem);
  } else {
    break
  }
}
console.log('After deletion', document.body.innerHTML)

or even better approach get all elements first then loop through them.或者更好的方法是先获取所有元素,然后循环遍历它们。

const tbodyElements = document.getElementsByTagName('tbody')
for (let i = 0; i < tbodyElements.length; i++) {
  if (!tbodyElements[i].innerHTML.trim()) {
    tbodyElements[i].parentNode.removeChild(tbodyElements[i]);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM