How to wait until an element exists?

后端 未结 19 1745
广开言路
广开言路 2020-11-22 09:14

I\'m working on an Extension in Chrome, and I\'m wondering: what\'s the best way to find out when an element comes into existence? Using plain javascript, with an interval t

19条回答
  •  渐次进展
    2020-11-22 09:42

    If you want it to stop looking after a while (timeout) then the following jQuery will work. It will time out after 10sec. I needed to use this code rather than pure JS because I needed to select an input via name and was having trouble implementing some of the other solutions.

     // Wait for element to exist.
    
        function imageLoaded(el, cb,time) {
    
            if ($(el).length) {
                // Element is now loaded.
    
                cb($(el));
    
                var imageInput =  $('input[name=product\\[image_location\\]]');
                console.log(imageInput);
    
            } else if(time < 10000) {
                // Repeat every 500ms.
                setTimeout(function() {
                   time = time+500;
    
                    imageLoaded(el, cb, time)
                }, 500);
            }
        };
    
        var time = 500;
    
        imageLoaded('input[name=product\\[image_location\\]]', function(el) {
    
         //do stuff here 
    
         },time);
    

提交回复
热议问题