删除当前<tr>并且还删除<tr>在使用纯javascript之前

delete the current <tr> and also delete the <tr> before it using plain javascript

本文关键字:删除 gt tr lt 之前 javascript      更新时间:2024-04-08

我有这样的HTML结构:

 <tr class="project-details">REMOVE THIS</tr>
<tr class="project-description">
  <td colspan="6">
    <div class="project-desc-inner">
      <div class="project-synopsis">
        <p class="trunk8">This is an entry</p>
      </div>
      <div class="project-verification">
        <span class="verfied-badge"> <~~~~~~~~~~ THIS SPAN
            <span class="currency-symbol">$</span>
            <span class="icon-tick"></span>
            Verified
        </span>
      </div>
      <div class="project-actions">
        <a href="#">
            <button class="btn">LOL</button>
        </a>
      </div>
    </div>
  </td>
</tr>

我希望整个<tr class="project-details">REMOVE THIS</tr>及其内容将被完全删除

这就是我目前所拥有的:

function showAlert()
{
var projectDescriptions = document.querySelectorAll('tr.project-description'),
    projectDescriptions = Array.prototype.slice.call(projectDescriptions); 
    projectDescriptions.forEach(function(el) { 
        if (el.querySelector('span.verfied-badge')) { 
        }else {
            el.parentNode.removeChild(el);
            el.prev('tr').remove();
        }
    });
}

它所做的是选择具有我要查找的<span><tr>,然后删除整个跨度。这部分el.prev('tr').remove();不工作,有其他选择吗?

谢谢!

else子句的主体:

(function removePreviousSibling(sibling) {
  if (sibling.nodeName === 'TR' && sibling.classList.contains('project-details')) {
    return sibling.parentNode.removeChild(sibling);
  }
  removePreviousSibling(sibling.previousSibling);
}(el.previousSibling));
el.parentNode.removeChild(el);

IIFE确保如果两个<tr>元素之间有一个额外的文本节点,那么如果您只是在目标元素的previousSibling上调用了removeChild,则该文本节点将被跳过而不会被删除。

请查看MDN的DOM页面上的信息。它有一套很棒的界面文档和教程。

prev是一个jQuery对象的方法。HTMLElement对象没有prev方法。为了选择上一个同级元素,可以使用previousElementSibling特性。