How can I tell if an element has not been loaded yet?

Discussion in 'JavaScript' started by Imozeb, Apr 4, 2010.

  1. #1
    I have a piece of code that needs an element. The element is dynamicly loaded so I need to check if it has been loaded so I can execute my script. How could I do this?

    This has not been giving me errors before, but now it is... strange

    Javascript Code:
    
    echeck = document.getElementById('etobechecked');
    if(echeck != null)
    {
      //code here
    }
    
    Code (markup):
     
    Imozeb, Apr 4, 2010 IP
  2. d_s

    d_s Peon

    Messages:
    22
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Hi,

    I have also used a similar method, it works fine for me.. Here is the code, you may give it a try,

    
    function loadelement() //to append an element to a form tag with id="F1"
        {
            var el = document.createElement("input");
            el.setAttribute("id","dynelement");
            el.setAttribute("type","button");
            el.setAttribute("value", "hi");
            el.setAttribute("onclick","test()");
            f1.appendChild(el);
        }
        
        function checkelement() //to check for the presence of this element.
        {
            if(document.getElementById("dynelement")!=null){
            alert("loaded");}
            else{
            alert("not yet loaded");}
        }
    
    ------------ the following is the html part for this -------
    <input type="button" id="b1" onclick="loadelement()" value="addelement" />
        <input type="button" id="check" onclick="checkelement()" value="Check for Element" />
    
    Code (markup):
    I am dubious that you may have invoked the checking script prior to appeding script.

    regards

    d_s.
     
    d_s, Apr 7, 2010 IP
  3. pixelz

    pixelz Greenhorn

    Messages:
    17
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #3
    you can try:
    if(document.getElementById("ElementID")){
    // your code
    }
     
    pixelz, Apr 10, 2010 IP
  4. Imozeb

    Imozeb Peon

    Messages:
    666
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Thanks, it worked!
     
    Imozeb, Apr 10, 2010 IP