Why does jQuery or a DOM method could not find the element?

As script executed line by line, they are only executed when they are added into the DOM. The order matters. This mean the script cant find the element which written later below as it is not added into the DOM yet. Example:


alert(document.getElementById("fname"));


<div id="fname">test</div>


alert(document.getElementById("fname")); 


The result for first document.getElementById is null. However, there is value for the second one.

What should you do?

There are few option to solve this.

        1. Move your script to where your action will be fire
          
              document.getElementById("fname").addEventListener("focusout", function() {
                alert(this.value);
              });
          
          
        2. Use $(document).ready()
          This will parse all the codes into the DOM first before executing them.

          
              $(document).ready(function(){
              $("#fname").focusout(function(){
                alert(document.getElementById("fname").value);
                });
              });
          
          
        3. Use Delegated Events .On()
          Delegated events can process events from descendant elements that are added to the document at a later time.

          
            $(document).on("click", {val: "test"}, display);
          
            function display( event ) {
            alert( "display: " + event.data.val );
          }
          
          click me
          

Either way can solve the problem.

Is best to use the $(document).ready(), this will ensure all events will be registered in DOM before executing them.

$(document).ready(function() {
   // do stuff when DOM is ready
});

or

$(function() {
    // do stuff when DOM is ready
});

For more information of this, refer here.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

×