Created
August 22, 2017 14:54
-
-
Save javierarques/3a4af27f31f4ebd9bcaeaaf34ce466ee to your computer and use it in GitHub Desktop.
waitUntilElementExists.js: Wait DOM element exists in the page with vanilla JS and Promises
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
const waitUntilElementExists = (DOMSelector, MAX_TIME = 10000) => { | |
let timeout = 0; | |
const waitForContainerElement = (resolve, reject) => { | |
const container = document.querySelector(DOMSelector); | |
timeout += 30; | |
if (timeout >= MAX_TIME) reject('Element not found'); | |
if (!container || container.length === 0) { | |
setTimeout(waitForContainerElement.bind(this, resolve, reject), 30); | |
} else { | |
resolve(container); | |
} | |
}; | |
return new Promise((resolve, reject) => { | |
waitForContainerElement(resolve, reject); | |
}); | |
}; |
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
describe('waitUntilElementExists', () => { | |
it('waits until a dom element is in the DOM', () => { | |
const elementId = 'elementId'; | |
const addElementDelayed = (delay) => { | |
window.setTimeout(() => { | |
const element = document.createElement('DIV'); | |
element.id = elementId; | |
window.document.body.appendChild(element); | |
}, delay); | |
}; | |
addElementDelayed(10); | |
return waitUntilElementExists(`#${elementId}`, 20) | |
.then((el) => { | |
expect(el.id).to.equal(elementId); | |
}) | |
.catch((error) => { | |
expect(error).to.equal('Element not found'); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment