***EDIT -- the issue appears to be in the way I'm trying to add a class (I tried changing some CSS for the class to test and it doesn't do anything)
I want to find an element in the DOM based on text, and add a class to it, so that I can manipulate it/its parent elements
This is the function I wrote to do this (before this I'm using a function from stackoverflow to walk through the DOM , and call my function to replace the matches- (the actual string values are not important right now) -- the HTML I'm modifying is the DOM.
var MATCH = ['word'];
var REPLACE = ['other'];
function replaceText(textNode) {
var badWord = textNode.nodeValue;
var replaceWord = "";
badWord.className = "filter";
//Go through and match/replace strings equal to MATCH
for (var i=0; i< MATCH.length; i++) {
replaceWord = document.getElementsByClassName("filter").innerHTML;
replaceWord = replaceWord.replace(new RegExp('\\b' + MATCH[i] + '\\b', 'g'), REPLACE[i]);
}
textNode.nodeValue = replaceWord;
}
It works when I just directly replace the text in the word like this below - but I want to access and modify from the class, so that I can change the parent elements/css
//working version without adding class
function hide(textNode) {
var badWord = textNode.nodeValue;
//Go through and match/replace strings equal to MATCH
for (var i=0; i< MATCH.length; i++) {
badWord = badWord.replace(new RegExp('\\b' + MATCH[i] + '\\b', 'g'), REPLACE[i]);
}
textNode.nodeValue = badWord;
}
function from stackoverflow post -
walk(document.body);
function walk(node) {
var child, next;
switch (node.nodeType) {
case ELEMENT: // Element
case DOCUMENT: // Document
case DOCUMENT_FRAGMENT: // Document fragment
child = node.firstChild;
while (child) {
next = child.nextSibling;
walk(child);
child = next;
}
break;
case TEXT: // Text node
replaceText(node);
break;
}
}