简体   繁体   中英

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

<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?

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="MainDescription2">text2</span> </div> </td> </tr> </tbody> </table>

You can use Array.filter to select elements by their content, using a function that checks the content of the element to see if it matches your required criteria. For example:

//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.
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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