greasemonkey/greasemonkey

Script not working as intended: trying to replace certain texts with this script

Closed this issue · 3 comments

So this is a script I found while googling.
(originally meant for code manipulator)
The purpose of it is to find an element via class name,
check if that class has certain text in it,
if so replace it with another text:

var elementsWithThisClassName = document.getElementsByClassName("classname");
for (var i = 0; i < elementsWithThisClassName.length; i++) {
    if (elementsWithThisClassName[i].innerHTML  == "the thing I want to replace") {
        elementsWithThisClassName[i].innerHTML = "replace with this"
    }
}

So this code usually works, but on the same site on the exact same page this code worked,
for some elements, it doesn't work.
I fail to see why it works on some and suddenly doesn't work on others.

If someone can tell me what is wrong or has a better script,
I would appreciate it

It is impossible to say why this does not work without an actual example on an actual page.

Have you tested this code in the browser console (control-shift-I, Console tab)? If it doesn't work there, then the issue is with the Javascript itself, not with Greasemonkey.

It seems extremely unlikely that this is an issue with Greasemonkey.

Some general Javascript tips:

  • Test and code in the console, you'll get live previews of what your code gets.
  • Use document.querySelectorAll('.classname') instead of the old syntax you found (document.getElementsByClassName("classname");).
  • Instead of an old for loop, use this: elements.forEach((element)=>{ here comes the code }
  • There may be an issue with subtle differences in the innerHTML that makes your == fail. You can make it a bit more fuzzy by using Regex, and explore that's actually in the html when it doesn't match. So use element.innerHTML = element.innerHTML.replace(/the thing I want to replace/gi, 'replace with this'). And explore why it doesn't match using Regex101.com.

It seems extremely unlikely that this is an issue with Greasemonkey.

Sorry, I thought this was the case but sort of assumed it would be fine to ask about scripts here

Instead of an old for loop, use this: elements.forEach((element)=>{ here comes the code }
So use element.innerHTML = element.innerHTML.replace(/the thing I want to replace/gi, 'replace with this')

I'm confused about this part, do I paste the latter to "here comes the code" ?

var elements = document.querySelectorAll(".classname");
elements.forEach( (element) => {
    element.innerHTML = element.innerHTML.replace(/unwanted html/gi, "new html");
});

So this will not solve your issue, just make the code more readable and modern. You can fiddle with the regex in the replace method to find out why some html is not being replaced as it should. Go to Regex101.com and experiment with the target html and the regex.