I'm making a Find and Replace chrome extension for on webpages, here's the find and replace code I have so far;
var elements = document.getElementsByTagName("*");
var find = "e";
var replace = "A";
for (var i = 0; i < elements.length; ++i) {
if (elements[i].childNodes[0] !== undefined && elements[i].childNodes[0].nodeType === 3) {
for (curText = elements[i].childNodes[0].nodeValue; curText !== curText.replace(find, replace); curText = curText.replace(find, replace)) {
elements[i].childNodes[0].nodeValue = curText;
}
}
}
the only problem is it doesn't replace every "e" in every location. There are e's leftover in links and in places like div and span tags on the inside. I get the feeling I'm not looping through all the elements correctly, I'm not detecting strings correct, and that I'm not replacing the found strings correct. How could I fix this problem?
EDIT: Alright, now, this is the current code. It works for the most part, the only problem is it doesn't work all over the page. You can open the JavaScript console and try it at
http://www.roblox.com/games/?SortFilter=default&TimeFilter=0&GenreFilter=1
The words on the side bar doesn't get changed.
var elements = document.getElementsByTagName("*");
var find = "e";
var replace = "A";
for (var i = 0; i < elements.length; ++i) {
if (elements[i].childNodes[0] !== undefined && elements[i].childNodes[0].nodeType === 3) {
elements[i].childNodes[0].nodeValue = elements[i].childNodes[0].nodeValue.replace(new RegExp(find, "g"), replace)
}
}
EDIT: Okay, new code now! undefined appears in the console, and nothing gets changed, I found this on a google search, it was from a stack overflow question. Find all text nodes in HTML page
Code:
var find = "e";
var replace = "A";
function textNodesUnder(el){
var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
while(n=walk.nextNode()) a.push(n);
return a;
}
var nodes = textNodesUnder(document.body);
for (var i = 0; i < elements.length; ++i) {
if (nodes[i].childNodes[0] !== undefined && elements[i].childNodes[0].nodeType === 3) {
nodes[i].childNodes[0].nodeValue = nodes[i].childNodes[0].nodeValue.replace(new RegExp(find, "g"), replace)
}
}
I have yet to test but it seems as I made a big mistake of leaving my childNodes precious code in the new one, without it, it should work.