I am getting an infinite loop for a function that was previously working -- I actually got this from a stackoverflow post (I'll link to it below). I don't understand why the slight changes I've made to it would cause an infinite loop.
Infinite loop version
function walk(node, filter) {
console.log("value of filter in walk "+ filter + " node: " + node);
var child, next;
if(node !== null && filter !== undefined) {
switch (node.nodeType) {
case Node.ELEMENT_NODE: // Element
case Node.DOCUMENT_NODE: // Document
case Node.DOCUMENT_FRAGMENT_NODE: // Document fragment
child = node.firstChild;
while (child) {
next = child.nextSibling;
walk(child, filter);
child = next;
}
break;
case Node.TEXT_NODE: // Text node
hide(node, filter);
break;
}
}//if statement
}
Working version
function walk(node) {
var child, next;
switch (node.nodeType) {
case Node.ELEMENT_NODE: // Element
case Node.DOCUMENT_NODE: // Document
case Node.DOCUMENT_FRAGMENT_NODE: // Document fragment
child = node.firstChild;
while (child) {
next = child.nextSibling;
walk(child);
child = next;
}
break;
case Node.TEXT_NODE: // Text node
hide(node);
break;
}
}
There is also a difference in how I'm calling the functions -- for the working version, it was simply:
walk(document.body);
For the new version, I have a function that gets the value for a filter from chrome.storage (this is only here to be passed into another function later) --
function walkWithFilter(){
chrome.storage.sync.get('theFilter', function(e){
var word = e.theFilter;
console.log(word);
if(word !== null){
walk(document.body, word);
}
});
}
however I've also tried getting rid of this and hard coding a value for filter and then passing it in like:
walk(document.body, filter);
This still gives the same infinite loop in walk, so I've narrowed the issue to the walk function.
Here's a link to the stackoverflow post I got the function from walkfunction
**** EDIT ****
here is the hide() function, it finds the 'filter' word in the DOM and hides its parent elements:
function hide(textNode, filter) {
var nodeValue = textNode.nodeValue;
for (var i=0; i < filter.length; i++) {
if(-1 != nodeValue.indexOf(filter[i])) {
textNode.parentNode.classList.add('filter');
//how to change the element by class name (test)
var x = document.getElementsByClassName('filter');
var i;
for (i = 0; i < x.length; i++) {
console.log("parent length loop");
x[i].style.backgroundColor = "red";
$('.filter').parent().parent().parent().parent().addClass("parent-filter");
$('.parent-filter').hide();
$('.parent-filter').css("background-color", "black");
}
$('.filter').parent().css("background-color", "red");
}
}
textNode.nodeValue = nodeValue;
}
I believe I am getting an infinite loop because when I run the script it won't stop printing the console.log statement in the beginning of the walk function thousands of times and crashes/becomes unresponsive. This is for a chrome extension if that's relevant.