Search for an element until found using JavaScript

Follow me!

If you like this article, go ahead and follow me on Twitter:

Follow @getButterfly

A nice piece of code to use for A/B testing to look for a certain element every 50 milliseconds, execute the code when found, then clear the interval loop. If the element is not found the loop is interrupted after 15 seconds.

var ytTimeoutId;

window.onload = function() {
    ytTimeoutId = setInterval(function() {
        // Check for a specific element ID
        if (document.getElementById('element')) {
            // Do stuff

    }, 50);

    setTimeout(function() {
    }, 15000);

Change the interval ping value or the general timeout value (15 seconds) as you see fit.

Find more JavaScript tutorials, code snippets and samples here.

πŸ‘‹ Added by Ciprian on Tuesday, September 19, 2017 in Blog. Last modified on Friday, September 15, 2017.


Contribute to this article by sharing your opinion on Twitter:

Unlimited Automated Page Speed Monitoring & Tracking.
Use SpeedFactor to track your website. It’s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started
Privacy Policy