How to execute a line check cycle in a document in Javascript?

I am trying to create code that will search for specific text, and if it is found, it will click a button. It should constantly check the string, but I'm struggling to find a way to do this. I am a complete beginner in 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(); } } } } 
+6
source share
3 answers

Just change your code a bit.

I assume you have such HTML?

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

You 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 constantly check. I recommend using setInterval.

 var interval = setInterval(function() { var textFound = findText(); if(textFound) { clearInterval(interval); } },50); 
+1
source

Regular expression:

 (new RegExp('word')).test(str) (new RegExp(/word/)).test(str) 

IndexOf:

 str.indexOf('word') !== -1 

Search () searches for a string for the specified value or regular expression and returns the match position.

 var n=str.search("word"); 

or

  var n-str.search(/word/); if(n>0) {} 

with window .find ()

 if (window.find("word", true)){} //code while(window.find("word",true){ //code } 
0
source

Why do you need to constantly check? You should get a different approach ... Or your script will be blocked by Chrome, for example, if it makes the page not responsible. You can time out as Taylor Hakes suggested ... Or just call the findText function attached to the onChange event in the div.

0
source

Source: https://habr.com/ru/post/945365/


All Articles