How to remove element by class only if it contains an element with some specified text?

2912 views javascript
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>

How can I remove element with class="Action Head" if span that's inside it with id="MainDescription" contains some specified text?

answered question

1 Answer

10

You can use the function querySelectorAll to gather the whole set of elements Action Head then loop over those elements and for each Action Head element get its span element.

With that span element check the attribute textContent.

This code snippet will remove only one 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="MainDescription">text2</span>
        </div>
      </td>
    </tr>
  </tbody>
</table>

posted this

Have an answer?

JD

Please login first before posting an answer.