如果元素包含具有某些指定文本的元素,如何逐个删除元素?

问题描述 投票:-1回答:2
<tr class="Action Head" data-index="1">
    <td class="Template">
        <div class="Description">
            <span class="Text Description" id="MainDescription">text</span>
        </div>
    </td>
</tr>

如果带有id =“MainDescription”的span包含一些指定的文本,如何使用class =“Action Head”删除元素?

javascript google-chrome-extension
2个回答
0
投票

您可以使用Array.filter按内容选择元素,使用检查元素内容的函数来查看它是否符合您的要求。例如:

//variable rowsToRemove will be an array that contains all the rows that contain
//a span with id MainDescription which contain the word 'text'

var rowsToRemove = [].filter.call(document.querySelectorAll('.Action.Head'), function(row){
    var mainDescriptionSpan = row.querySelector('span#MainDescription');
    return (mainDescriptionSpan && mainDescriptionSpan.textContent.indexOf('text') != -1);
});

if (rowsToRemove.length) {  //if there are some row(s) that match the criteria...
    rowsToRemove.forEach(function(row){  // ... loop through all of them ...
        row.remove();  // ... and remove them.
    });
}

0
投票

您可以使用函数querySelectorAll来收集整个元素集Action Head然后循环遍历这些元素,并为每个Action Head元素获取其span元素。

使用span元素检查属性textContent

此代码段只会删除一个TR。

var actions = document.querySelectorAll('.Action.Head');
Array.prototype.forEach.call(actions, function(action) {
  var span = action.querySelector('span');
  if (span.textContent === 'text') span.remove();
});
<table>
  <tbody>
    <tr class="Action Head" data-index="1">
      <td class="Template">
        <div class="Description">
          <span class="Text Description" id="MainDescription">text</span>
        </div>
      </td>
    </tr>
    
    <tr class="Action Head" data-index="1">
      <td class="Template">
        <div class="Description">
          <span class="Text Description" id="MainDescription2">text2</span>
        </div>
      </td>
    </tr>
  </tbody>
</table>
© www.soinside.com 2019 - 2024. All rights reserved.