Skip to content

Instantly share code, notes, and snippets.

@javierarques
Created August 22, 2017 14:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javierarques/3a4af27f31f4ebd9bcaeaaf34ce466ee to your computer and use it in GitHub Desktop.
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
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);
});
};
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