Search code examples
javascripttampermonkey

how to click a specific text in the page JAVASCRIPT


after trying many ways to detect a specific word in the page and auto click on it ..so far i have

var items = document.body.getElementsByTagName("*");
for (var i = 0; i < items.length; ++i) {
    if (items[0].textContent == "my text or word") {
        items[0].click();
    }
}

the latest code seems work only for the first time (one time) but after refresh nothing happened i dont know what wrong


Solution

  • For some reason I have mixed success with document.body.getElementsByTagName("*"), so the below code uses either document.all OR document.body.getElementsByTagName("*") depending on which is supported.

    You were using [0] as your index when it should have been the variable [i]. Also, you can use the method .includes which will search for a substring (a string within a string), making it more likely you will find the element you are looking for. Just tested the below in firefox console and seems to work fine.

     if (document.all !== undefined)
        {
          var items = document.all;
        }
        else
        {
          var items = document.getElementsByTagName("*");
        };                    
            for (var i = 0; i < items.length; ++i) {
            if (items[i].textContent.includes("Your Text Here")) {
                console.log("success"); 
                items[i].click();
            }
        }