Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop a check for string in a document in Javascript?

I'm trying to make a code that will search for a specific text, and if it is found it will click a button. It needs to check for the string continuously, however I am struggling to find a way for that to happen. I'm a complete newb to coding, so any help is appreciated! :)

var findMe = [
    //Test
    'Hello!',
];

function findText() {
    var text = document.querySelector('div[id=BtnText]');

    for (var i = 0; i < findMe.length; i++) {
        if (BtnText.match(findMe[i])) {
            var btnDo = document.querySelector('input[type="submit"][value="Click!"]');
            if (btnDo) {
                btnDo.click();
            }
        }
    }
}
like image 253
user2399007 Avatar asked May 19 '13 14:05

user2399007


People also ask

Can you loop through a string in JavaScript?

Use the string index number to loop through a string In this loop, the variable i automatically receives the index so that each character can be accessed using str[i] .

How for in loop works in JavaScript?

A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. When a for loop executes, the following occurs: The initializing expression initialExpression , if any, is executed.

Which JavaScript loop ensures that at least a singular iteration will happen?

while loop, condition is checked at the end of each iteration of the loop, rather than at the beginning before the loop runs. This means that code in a do... while loop is guaranteed to run at least once, even if the condition expression already evaluates to true .


1 Answers

Just editing your code a little bit.

I am assuming you have HTML like this?

<div id="BtnText">Hello!</div><input type="submit" value="Click!">

You will to change your code to this

var findMe = [
    //Test
    'Hello!',
];

function findText() {
    var div = document.querySelector('div[id=BtnText]');

    for (var i = 0; i < findMe.length; i++) {
        if (div.innerText.indexOf(findMe[i]) !== -1) {               
            var btnDo = document.querySelector('input[type="submit"][value="Click!"]');
            if (btnDo) {
                if (typeof btnDo.onclick == "function") {
                    btnDo.onclick.apply(elem);
                }
            }
            return true;
        }
    }
    return false;
}

If you want to check continuously. I recommend using setInterval.

var interval = setInterval(function() {
   var textFound = findText();
   if(textFound) {
       clearInterval(interval);
   }
},50);
like image 161
Taylor Hakes Avatar answered Oct 13 '22 01:10

Taylor Hakes