仅当元素包含带有某些指定文本的元素时,才如何按类删除元素?

时间:2018-09-16 01:40:23

标签: javascript google-chrome-extension

<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”内部的跨度包含某些指定的文本,该如何删除class =“ Action Head”的元素?

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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.
    });
}
相关问题