Last active
December 23, 2016 06:00
-
-
Save Bahm/34593af1ad1a75161064201075027595 to your computer and use it in GitHub Desktop.
waitForElementToExist and waitForElementsToExist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// selector: string CSS selector, e.g., "#comment-section" or "div.comment, #user-id". | |
// action: function Function to call when an element matches the selector. | |
function waitForElementToExist(selector, action) { | |
var elm = document.querySelector(selector); | |
if(elm !== null) | |
action(elm); | |
else | |
setTimeout(waitForElementToExist.bind(null, selector, action), 100); | |
} | |
// selectors: array Array of CSS selector, e.g., ["body.logged-in", "#logout-button"]. | |
// action: function Function to call when ALL selectors match elements. | |
function waitForElementsToExist(selectors, action) { | |
var elms = selectors.every(s => document.querySelector(s)); | |
if(elms.every(e => e !== null)) | |
action(elms); | |
else | |
setTimeout(waitForElementsToExist.bind(null, selectors, action), 100); | |
} | |
// Wait for button to exist, then click it. | |
waitForElementToExist("#submit-button", function(submitBtn){ | |
console.log("Clicking submit!"); | |
submitBtn.click(); | |
}); | |
// You don't have to use the element you're waiting for. | |
var loggedIn = false; | |
waitForElementToExist("div.logged-in", function(){ | |
console.log("You are logged in!"); | |
loggedIn = true; | |
}); | |
// Never finishes; logs nothing | |
waitForElementsToExist( ["div.logged-in", ".non-existent-class"], | |
console.log.bind(console) ); | |
// Logs array of elements | |
waitForElementsToExist( ["div.logged-in", "#start-of-content"], | |
console.log.bind(console) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment