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!
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])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With