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.

 

One thought on “Why does jQuery or a DOM method could not find the element?

  1. Pingback: How to Use Window.onload() Event – Web / Application Development Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s