Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove elements that directly contain a string - ignoring child elements

I am trying to work out how to remove elements on a page that contain a certain string using plain JavaScript.

Here is the code I have so far:

var elements = document.querySelectorAll("body > *");
for (var i = 0, len = elements.length; i < len; i++) {
    var current = elements[i];

    if (current.innerHTML.indexOf("Word") !== -1) {
        current.parentNode.removeChild(current);
    }
}

This is able to remove elements that contain the phrase "word". However, it digs down into a divs child nodes and returns true if the children contain the string.

How could I change this so that it checks if an element directly contains the string and ignores the children whilst searching the current element.

The code should still search every element but just not go into the child nodes.

Does not return -1 (Returns true to containing the word):

<div>Word</div>

<p>Word</p>

Does return -1 (Returns false to containing the word):

<div><p>Word</p></div>

<div><div>Word</div></div>

Would really appreciate any help with this, thank you!

like image 448
Osman Avatar asked Apr 23 '26 02:04

Osman


1 Answers

var word = "Word"
var elements = document.querySelectorAll("body > *");
function removeContainingText(element) {
  var children = Array.from(element.childNodes)
  for (var i = 0; i<children.length; ++i){
    if (children[i].nodeType == 3){
        if (children[i].nodeValue.indexOf(word) !== -1) {
            children[i].parentNode.removeChild(children[i]);
        }
    }
  }
}
for (var k = 0; k < elements.length; ++k){
    removeContainingText(elements[k])   
}
like image 99
Kshitij Mittal Avatar answered Apr 25 '26 15:04

Kshitij Mittal